package com.ysd.lis.service.lab.impl;

import cn.com.jit.ida.util.pki.encoders.Base64;
import cn.com.jit.new_vstk.AdvanceSignClient;
import cn.com.jit.new_vstk.Bean.SymmKeyNo;
import cn.com.jit.new_vstk.Bean.SymmKeyParams;
import cn.com.jit.new_vstk.config.NewConfig;
import cn.com.jit.new_vstk.exception.NewCSSException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.enums.ChkStatusEnum;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.bac.BacAddFee;
import com.ysd.lis.entity.bac.BacDrugTestResult;
import com.ysd.lis.entity.bac.BacTestWorkFlowNode;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.pub.PubReportMapper;
import com.ysd.lis.mapper.pub.PubReportRulesMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMethExtParamMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMethodMapper;
import com.ysd.lis.request.*;
import com.ysd.lis.request.lab.*;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.SysUserService;
import com.ysd.lis.service.bac.BacRuleService;
import com.ysd.lis.service.bac.BacTestWorkFlowNodeService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.lab.*;
import com.ysd.lis.util.InterfaceUtil;
import com.ysd.lis.util.lab.CalcItemFormulaReplcae;
import com.ysd.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Cfz
 * @since 2023-12-26
 */
@Service
public class LabMaininfoServiceImpl extends ServiceImpl<LabMaininfoMapper, LabMaininfo> implements LabMaininfoService {
    private static final Logger logger = LoggerFactory.getLogger(LabMaininfoServiceImpl.class);

    @Autowired
    LabReqMainMapper labReqMainMapper;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Autowired
    LabRptresultMapper labRptresultMapper;

    @Autowired
    LabRptresultImageMapper labRptresultImageMapper;

    @Autowired
    LabRptresultImageService labRptresultImageService;

    @Autowired
    LabRptmainMapper labRptmainMapper;

    @Autowired
    LabRptdetailMapper labRptdetailMapper;

    @Autowired
    PubReportRulesMapper reportRulesMapper;

    @Autowired
    LabRulesVsItemdictMapper rulesVsItemdictMapper;

    @Autowired
    LabReqStateService labReqStateService;

    @Autowired
    LabMainStateService labMainStateService;

    @Autowired
    LabRptGroupMapper labRptGroupMapper;

    @Autowired
    LabRptresultService labRptresultService;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    SysParamValueService sysParamValueService;

    @Autowired
    LabTemplateService labTemplateService;

    @Autowired
    LabResultAmendmentMapper labResultAmendmentMapper;

    @Autowired
    LabResultAmendmentService labResultAmendmentService;

    @Autowired
    LabMaininfoCancleauditService labMaininfoCancleauditService;

    @Autowired
    BacTestResultMapper bacTestResultMapper;
    @Autowired
    BacStainingResultMapper bacStainingResultMapper;
    @Autowired
    BacDrugTestResultMapper bacDrugTestResultMapper;
    @Autowired
    BacObserResultMapper bacObserResultMapper;
    @Autowired
    LabRptdetailBacService labRptdetailBacService;
    @Autowired
    LabRptdetailStainingService labRptdetailStainingService;
    @Autowired
    LabRptdetailDrugService labRptdetailDrugService;
    @Autowired
    LabRptdetailObserService labRptdetailObserService;
    @Autowired
    LabMaininfoService labMaininfoService;

    @Autowired
    SysInterfaceMethodMapper sysInterfaceMethodMapper;

    @Autowired
    SysInterfaceMethExtParamMapper sysInterfaceMethExtParamMapper;

    @Autowired
    LabMainInfoServiceBakImpl labMainInfoServiceBak;

    @Autowired
    LabMaininfoServiceExtendImpl labMaininfoServiceExtend;

    @Autowired
    LabMaininfoExcelServiceImpl labMaininfoExcelService;

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Autowired
    LabReqMainService labReqMainService;

    @Autowired
    LabMaininfoServiceQueryImpl labMaininfoServiceQuery;

    @Autowired
    BacRuleService bacRuleService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    private InterfaceUtil interfaceUtil;
    @Autowired
    RedisSysParamHelper redisSysParamHelper;

    @Autowired
    LabMaininfoBacServiceImpl labMaininfoBacServiceImpl;

    @Value("${mybatis-plus.configuration.page-type}")
    private String pageType;

    @Autowired
    PubReportMapper pubReportMapper;

    @Autowired
    LabFeeitemVsItemDictMapper labFeeitemVsItemDictMapper;
    @Autowired
    BacTestWorkFlowNodeService bacTestWorkFlowNodeService;
    /**
     * 初步审核
     */
    public static final String PRELIMINARY_REVIEW = "1";
    /**
     * 取消初步审核
     */
    public static final String CANCEL_PRELIMINARY_REVIEW = "2";
    /**
     * 审核
     */
    public static final String REVIEW = "3";

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public Result insertMaininfoByReqNo(AddLabMaininfo labReqMain) throws JsonProcessingException {
        String reqno = labReqMain.getReqNo();
        String rptGroup = labReqMain.getRptGroup();
        long l = System.currentTimeMillis();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);

        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(LabReqMain.class).selectAs(LabSampleType::getSampleTypeName, LabReqMain::getSampleTypeNa).selectAs(LabSampleType::getInfectSiteNo, LabReqMain::getInfectSiteNo).leftJoin(LabSampleType.class, it -> it.eq(LabSampleType::getSampleTypeCode, LabReqMain::getSampleType).eq(LabSampleType::getDelFlag, 0)).eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, reqno).orderByDesc(LabReqMain::getCreateTime);

        List<LabReqMain> reqMains = labReqMainMapper.selectList(queryWrapper);
        LabReqMain reqMain = reqMains.isEmpty() ? null : reqMains.get(0);
        if (reqMain == null && StringUtils.isNotBlank(reqno)) {
            try {
                Result rsult = labMainInfoServiceBak.getApiReqMainInfo(labReqMain);
                if ("400".equals(rsult.getStatus().get("code") + "")) {
                    throw new RuntimeException(rsult.getStatus().get("msg") + "");
                }
            } catch (Exception e) {
                throw e;
            }

            reqMain = labMainInfoServiceBak.getLabReqMainEntity(reqno);//labReqMainMapper.selectOne(queryWrapper);
            if (reqMain == null) {
                throw new RuntimeException("未获取到申请信息！");
            }
        }
        /*验证系统参数，无条码号，禁止创建上机记录 2025-04-15 青岛优抚 王超提出需求，彭大jb分派*/
        SysParamParam sysp1111 = new SysParamParam();
        sysp1111.setParamCode("xtxxcs");
        sysp1111.setField("wtmhjzcjsjjl");
        List<SysParamFieldValueDto> r111 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1111);
        if (!r111.isEmpty()) {
            if ("1".equals(r111.get(0).getValue()) && StringUtils.isBlank(reqno)) {
                return Result.fail("无条码号禁止创建上机记录");
            }
        }
        //申请信息不为空判断报告单元下是否存在禁用申请项目
        boolean haveBanFeeItem = labMainInfoServiceBak.haveBanFeeItem(rptGroup, reqno);
        if (haveBanFeeItem) {
            return Result.fail("该报告单元下存在禁用申请项目，不能上机！");
        }

        /*验证系统参数，东北双塔取消上机退费后2025-03-20，禁止上机*/
        SysParamParam sysp0 = new SysParamParam();
        sysp0.setParamCode("xtxxcs");
        sysp0.setField("qxsjreturnfeenocheck");
        List<SysParamFieldValueDto> r0 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp0);
        if (!r0.isEmpty()) {
            if ("1".equals(r0.get(0).getValue()) && "1".equals(reqMain.getIsCancel() + "")) {
                return Result.fail("已取消上机退费，无法再次上机");
            }
        }

        //TODO 判断当前申请的状态，如果已经作废的不允许上机
        if (!BeanUtil.isEmpty(reqMain)) {
            try {
                if (!BeanUtil.isEmpty(reqMain.getIsCancel()) && reqMain.getIsCancel().equals(1)) {
                    return Result.fail("当前标本已经作废," + reqMain.getCancelReason());
                }
            } catch (Exception ex) {
                //TODO
            }

            /*验证系统参数，无签收时间，禁止上机*/
            SysParamParam sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("wqssjbbjzsj");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(reqMain.getSignTime())) {
                    return Result.fail("无签收时间标本禁止上机");
                }
            }

            //住院无签收时间标本禁止上机
            /*验证系统参数，无签收时间，禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("zywqssjbbjzsj");
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(reqMain.getSignTime()) && !BeanUtil.isEmpty(reqMain.getPatType()) && reqMain.getPatType().equals("3")) {
                    return Result.fail("住院无签收时间标本禁止上机");
                }
            }

            /*验证系统参数，无采样时间,禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("wcysjjzsj");
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    List<String> listValue = getListValueMethod(value);
                    if (ToolsUtils.isNotEmpty(reqMain.getPatType()) && listValue.contains(reqMain.getPatType()) && ToolsUtils.isEmpty(reqMain.getSamplingTime())) {
                        return Result.fail("无采样时间禁止上机");
                    }
                }
            }

            /*验证系统参数，无采样人,禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("wcyrjzsj");
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    List<String> listValue = getListValueMethod(value);
                    if (ToolsUtils.isNotEmpty(reqMain.getPatType()) && listValue.contains(reqMain.getPatType()) && ToolsUtils.isEmpty(reqMain.getSamplingDoctor())) {
                        return Result.fail("无采样人禁止上机");
                    }
                }
            }

            //---报告单元
            /*验证系统参数，无采样时间,禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("bgdyxtcs");
            sysp1.setField("bgdywcysjjzsj");
            sysp1.setClassifyCode(labReqMain.getRptGroup());

            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    List<String> listValue = getListValueMethod(value);
                    if (ToolsUtils.isNotEmpty(reqMain.getPatType()) && listValue.contains(reqMain.getPatType()) && ToolsUtils.isEmpty(reqMain.getSamplingTime())) {
                        return Result.fail("无采样时间禁止上机");
                    }
                }
            }
            //---报告单元
            /*验证系统参数，无采样人,禁止上机*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("bgdyxtcs");
            sysp1.setField("bgdywcyrjzsj");
            sysp1.setClassifyCode(labReqMain.getRptGroup());
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    List<String> listValue = getListValueMethod(value);
                    if (ToolsUtils.isNotEmpty(reqMain.getPatType()) && listValue.contains(reqMain.getPatType()) && ToolsUtils.isEmpty(reqMain.getSamplingDoctor())) {
                        return Result.fail("无采样人禁止上机");
                    }
                }
            }
        }


        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // if (!BeanUtil.isEmpty(labReqMain.getReqNo())) {
        //     lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getReqNo, labReqMain.getReqNo()).eq(LabMaininfo::getRptGroup, labReqMain.getRptGroup()).eq(LabMaininfo::getSampleda, labReqMain.getSampleda()).eq(LabMaininfo::getSampleNo, labReqMain.getSampleNo());
        // } else {
        lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getRptGroup, labReqMain.getRptGroup()).eq(LabMaininfo::getSampleda, labReqMain.getSampleda()).eq(LabMaininfo::getSampleNo, labReqMain.getSampleNo());
        // }

        //检查标本号重复上机
        List<LabMaininfo> labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
        /*条码号为空*/
        if (!labMainInfoList.isEmpty()) {
            /*同意报告单元  检验日期 不能有重复标本号*/
            //if (BeanUtil.isEmpty(labReqMain.getReqNo())) {
            return Result.fail("同一天，同一报告单元，标本号不允许重复!");
            //}
        }

        //TODO 条码号重复上机，根据系统选项判断是否允许上机还是提示
        try {
            SysParamParam kcflrdstndtm = new SysParamParam();
            /*可重复录入多少天内的条码 kcflrdstndtm*/
            kcflrdstndtm = new SysParamParam();
            kcflrdstndtm.setParamCode("bgdyxtcs");
            kcflrdstndtm.setField("kcflrdstndtm");
            kcflrdstndtm.setClassifyCode(labReqMain.getRptGroup());
            List<SysParamFieldValueDto> kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(kcflrdstndtm);
            String kcflrdstndtmStr = kcflrdstndtmLst.get(0).getValue();

            /*扫码时不提示重复使用 smsbtscfsy*/
            kcflrdstndtm = new SysParamParam();
            kcflrdstndtm.setParamCode("bgdyxtcs");
            kcflrdstndtm.setField("smsbtscfsy");
            kcflrdstndtm.setClassifyCode(labReqMain.getRptGroup());
            List<SysParamFieldValueDto> smsbtscfsy = sysParamValueService.findSysParamFieldAndValueListByCode(kcflrdstndtm);
            String smsbtscfsyStr = smsbtscfsy.get(0).getValue();

            if (!BeanUtil.isEmpty(reqno)) {
                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
                lambdaQueryWrapper.eq(LabMaininfo::getReqNo, reqno);

                //检查标本号重复上机
                labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
                if (!BeanUtil.isEmpty(kcflrdstndtmStr) && kcflrdstndtmStr.equals("2") && !labMainInfoList.isEmpty()) {
                    return Result.fail("条码号已上机，禁止重复上机");
                }

                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
                lambdaQueryWrapper.eq(LabMaininfo::getReqNo, reqno);
                lambdaQueryWrapper.eq(LabMaininfo::getRptGroup, labReqMain.getRptGroup());
                labMainInfoList = labMaininfoMapper.selectList(lambdaQueryWrapper);
                if (!BeanUtil.isEmpty(kcflrdstndtmStr) && kcflrdstndtmStr.equals("3") && !labMainInfoList.isEmpty()) {
                    return Result.fail("该报告单元内本条码号已上机，禁止重复上机");
                }
            }
        } catch (Exception e) {
            //ToDo
        }

        int configSpecScheduleDays = 30;


        try {
            /*扫码上机时允许的检验日期天数 smsjsyxdjyrqts*/
            SysParamParam smsjsyxdjyrqts = new SysParamParam();
            smsjsyxdjyrqts.setParamCode("bgdyxtcs");
            smsjsyxdjyrqts.setField("smsjsyxdjyrqts");
            smsjsyxdjyrqts.setClassifyCode(labReqMain.getRptGroup());
            List<SysParamFieldValueDto> smsjsyxdjyrqtsLst = sysParamValueService.findSysParamFieldAndValueListByCode(smsjsyxdjyrqts);
            String smsjsyxdjyrqtsStr = smsjsyxdjyrqtsLst.get(0).getValue();
            configSpecScheduleDays = Integer.parseInt(smsjsyxdjyrqtsStr);
        } catch (Exception e) {
            configSpecScheduleDays = 30;
        }

        SysUser sysUser = RedisUserManager.getUser();
        //扫码上机时允许的检验日期天数
        Date now = new Date();
        Timestamp sampleda = labReqMain.getSampleda();

        Date date = timeToDate(sampleda);

        int days = differentDaysByMillisecond(date, now);
        if (days > configSpecScheduleDays) {
            return Result.fail("检验日期超出设定值" + days + "天，禁止上机!");
        }

        //扫码上机从lab_reqmain里取数据存入上机表中
        LabMaininfo labMaininfo = new LabMaininfo();
        if (!BeanUtil.isEmpty(labReqMain.getTestDoctor())) {
            labMaininfo.setTestDoctor(labReqMain.getTestDoctor());
        } else {
            labMaininfo.setTestDoctor(sysUser.getUsername());

        }

        /*上机时自动补充签收时间*/
        SysParamParam sysp1 = new SysParamParam();
        sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("sjszdbcqssj");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        if (!r1.isEmpty()) {
            if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(labMaininfo.getSignTime())) {
                labMaininfo.setSignerDoctor(sysUser.getUsername());
                labMaininfo.setSignTime(new Timestamp(System.currentTimeMillis()));
            }
        }
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, orgId);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        if (!BeanUtil.isEmpty(reqMain)) {
            if (!r1.isEmpty()) {
                logger.info("开始执行扫码上机签收更新医嘱状态接口");
                /*上机时自动补充申请签收时间*/
                if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(reqMain.getSignTime())) {
                    logger.info("开始执行扫码上机签收更新医嘱状态接口22222222222222");
                    reqMain.setSignerDoctor(sysUser.getUsername());
                    reqMain.setSignTime(new Timestamp(System.currentTimeMillis()));
                    reqMain.setSignerNa(sysUser.getRealname());
                    reqMain.setIsSign(new BigDecimal(1));
                    labReqMainService.updateById(reqMain);
                    //开始上机医嘱状态更
                    if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                        /*发布报告相关*/
                        for (String webUrl : collect) {
                            //调用修改状态接口
                            String updateUrl = webUrl + "/public/updateReportStatus";
                            Map<String, Object> updateMap = new HashMap<>();
                            updateMap.put("status", "0304");//签收
                            updateMap.put("reqNo", reqMain.getReqNo());
                            updateMap.put("username", sysUser.getUsername());
                            updateMap.put("realname", sysUser.getRealname());
                            updateMap.put("orgId", sysUser.getOrgId());
                            updateMap.put("patType", reqMain.getPatType());
                            logger.info("开始执行扫码上机签收更新医嘱状态接口入参为:" + JSONUtil.toJsonStr(updateMap));
                            HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            if ("3".equals(reqMain.getPatType())) {
                                String updateUrlHl7 = webUrl + "/public/sampleReceive";
                                HttpUtil.createPost(updateUrlHl7).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            }
                        }
                    }
                }
            }
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                /*发布报告相关*/
                for (String webUrl : collect) {
                    //添加系统参数判断是否需要重新获取计费信息，（东北双塔天健接口需求）2025-03-18
                    /*添加系统参数判断是否需要重新获取计费信息*/
                    SysParamParam sysp111 = new SysParamParam();
                    sysp111.setParamCode("xtxxcs");
                    sysp111.setField("smsjsfxycxlqsq");
                    List<SysParamFieldValueDto> xtcs1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp111);
                    if (!xtcs1.isEmpty()) {
                        if (xtcs1.get(0).getValue().equals("1")) {
                            Map<String, Object> updateMap = new HashMap<>();
                            updateMap.put("reqNo", reqMain.getReqNo());
                            updateMap.put("username", sysUser.getUsername());
                            updateMap.put("realname", sysUser.getRealname());
                            updateMap.put("orgId", sysUser.getOrgId());
                            updateMap.put("patType", reqMain.getPatType());
                            logger.info("开始执行上机计费接口:" + JSONUtil.toJsonStr(updateMap));
                            String addFeeUrl = webUrl + "/public/beginCheckAddFee";
                            String body = HttpUtil.createPost(addFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                            JSONObject jsonObject = new JSONObject(body);
                            JSONObject status = jsonObject.getJSONObject("status");
                            String code = status.get("code").toString();
                            if ("400".equals(code)) {
                                return Result.fail(jsonObject.getStr("data"));
                            }
                        }
                    }
                }
            }
            /*检验医师为空时取当前登录人（前端）*/
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("jyyswkqdqdlr");
            r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if ("1".equals(r1.get(0).getValue()) && BeanUtil.isEmpty(labReqMain.getTestDoctor())) {
                    labMaininfo.setTestDoctor(sysUser.getUsername());
                }
            }
        }

        if (reqMain != null) {
            BeanUtil.copyProperties(reqMain, labMaininfo, "id", "isPrint", "printTime", "printDoctor", "creator", "editor", "createTime", "editTime", "delFlag");
        } else {
            labMaininfo.setRptGroup(labReqMain.getRptGroup());
            labMaininfo.setSampleda(labReqMain.getSampleda());
            labMaininfo.setSampleNo(labReqMain.getSampleNo());
        }
        labMaininfo.setTestTime(new Timestamp(System.currentTimeMillis()));

        if (StringUtils.isNotBlank(labMaininfo.getPatNa())) {
            String apply = PinYinUtil.firstPinYinFun.apply(labMaininfo.getPatNa());
            labMaininfo.setPatPyName(apply);
        }

        if (reqMain != null) {
            labMaininfo.setRemark1(reqMain.getRemark1());
            labMaininfo.setRemark2(reqMain.getRemark2());
            labMaininfo.setRemark3(reqMain.getRemark3());
            labMaininfo.setRemark4(reqMain.getRemark4());
            labMaininfo.setInfectSiteNo(reqMain.getInfectSiteNo());
            labMaininfo.setRptGroup(labReqMain.getRptGroup());
            labMaininfo.setSampleNo(labReqMain.getSampleNo());
            labMaininfo.setSampleda(labReqMain.getSampleda());
            labMaininfo.setOrgId(sysUser.getOrgId());
            labMaininfo.setIsChk(new BigDecimal(0));
        }
        if (StringUtils.isNotBlank(labReqMain.getChkDoctor())) {
            labMaininfo.setChkDoctor(labReqMain.getChkDoctor());
        }

        if (labMaininfo.getSampleType() == null) {
            //如果标本类型是空的，设置默认类型
            //TODO
        }

        //改修改
        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
        lambdaQueryWrappers.eq(LabMaininfo::getSampleNo, labMaininfo.getSampleNo()).eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup()).eq(LabMaininfo::getSampleda, labMaininfo.getSampleda()).eq(LabMaininfo::getDelFlag, 0);
        boolean b = labMaininfoService.saveOrUpdate(labMaininfo, lambdaQueryWrappers);


        /*微生物扫码上机，计算方案、选用的培养基*/
        if (BeanUtil.isNotEmpty(labReqMain) && StringUtils.isNotBlank(labReqMain.getDataType()) && "2".equals(labReqMain.getDataType())) {
            if (ToolsUtils.isNotEmpty(reqMain) && StringUtils.isBlank(reqMain.getPurposeNo())) {
                labReqMainService.bacCalcPurposeByScanReqNo(reqMain, labMaininfo);
            } else if (ToolsUtils.isNotEmpty(reqMain) && StringUtils.isNotBlank(reqMain.getPurposeNo())) {
                //已走签收
                labReqMainService.bacTestUpdateWorkFlowV1(reqMain, labMaininfo);
            } else if (ToolsUtils.isEmpty(reqMain)) {
                //无申请，默认细菌检验
                labReqMainService.bacTestUseDefaultWorkFlowWithPurpose(reqMain, labMaininfo);
            } else {
                labReqMainService.bacTestUseDefaultWorkFlowWithPurpose(reqMain, labMaininfo);
            }
        }

        /*微生物扫码上机，采用默认方案、无培养基*/

        if (!"4".equals(labMaininfo.getPatType())) {
            try {
                if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                    for (String webUrl : collect) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.set("id", labMaininfo.getId());
                        jsonObject.set("username", sysUser.getUsername());
                        jsonObject.set("realname", sysUser.getRealname());
                        jsonObject.set("reqNo", labMaininfo.getReqNo());
                        String body = HttpUtil.createPost(webUrl + "/lisRestFul/noticeHisFee").body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                        logger.info(body);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (b) {
            //插入模板数据
            TemplateParams tmpParam = new TemplateParams();
            tmpParam.setMaininfoId(labMaininfo.getId());
            tmpParam.setRptGroup(labMaininfo.getRptGroup());
            tmpParam.setSampleda(labMaininfo.getSampleda());
            tmpParam.setSampleNo(labMaininfo.getSampleNo());
            tmpParam.setReqNo(reqno);
            labTemplateService.batchInsertDefItemDictAndTemplate(tmpParam);

            /*标本流程状态记录*/
            new Thread(() -> {
                //重新计算检验结果
                labRptresultService.reCalcRptRssults(labMaininfo);
                //上机之后插入状态信息
                LabMainState reqState1 = new LabMainState();
                reqState1.setMaininfoId(labMaininfo.getId());
                reqState1.setStateCode("90");
                reqState1.setStateValue("标本上机");
                reqState1.setOrgId(labMaininfo.getOrgId());
                labMainStateService.save(reqState1);

                if (StringUtils.isNotBlank(labMaininfo.getReqNo())) {
                    /*标本状态*/
                    LabReqMain rmEntry = labMainInfoServiceBak.getLabReqMainEntity(labMaininfo.getReqNo());
                    LabReqState reqState = new LabReqState();
                    reqState.setReqMainId(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getId() : "");
                    reqState.setSampleda(labMaininfo.getSampleda());
                    reqState.setSampleNo(labMaininfo.getSampleNo());
                    reqState.setRptGroup(labMaininfo.getRptGroup());
                    reqState.setReqNo(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                    reqState.setOrgId(labMaininfo.getOrgId());
                    reqState.setCreator(sysUser.getId());
                    reqState.setStateCode("90");
                    reqState.setStateValue("标本上机");
                    String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "标本上机,标本号:" + (BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                    reqState.setRemark(rmk);
                    reqState.setSeq(labReqStateService.getMaxCount(labMaininfo.getReqNo()));
                    labReqStateService.save(reqState);

                    if (BeanUtil.isNotEmpty(rmEntry)) {
                        rmEntry.setState("90");
                        rmEntry.setStateNa("标本上机");
                        labReqMainService.saveOrUpdate(rmEntry);
                    }
                }
            }).start();

            //开始上机医嘱状态更新
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect) && ToolsUtils.isNotEmpty(reqMain)) {
                /*发布报告相关*/
                for (String webUrl : collect) {
                    //调用修改状态接口
                    String updateUrl = webUrl + "/public/updateReportStatus";
                    Map<String, Object> updateMap = new HashMap<>();
                    //上机
                    updateMap.put("status", "0305");
                    updateMap.put("reqNo", reqMain.getReqNo());
                    updateMap.put("username", sysUser.getUsername());
                    updateMap.put("realname", sysUser.getRealname());
                    updateMap.put("orgId", sysUser.getOrgId());
                    updateMap.put("patType", reqMain.getPatType());
                    updateMap.put("chargeType", "1");
                    logger.info("开始上机更新医嘱状态入参为:" + JSONUtil.toJsonStr(updateMap));
                    HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                    //调用执行医嘱确费接口
                    if ("3".equals(reqMain.getPatType())) {
                        String yzqfUrl = webUrl + "/yzqf";
                        HttpUtil.createPost(yzqfUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                    }
                }
            }
            //调用开始上机接口
            try {
                String code = "BEGIN_CHECK";
                List<SysInterfaceDict> allSysInterfaceDict = interfaceUtil.getAllSysInterfaceDict(code);
                if (CollectionUtils.isNotEmpty(allSysInterfaceDict) && ToolsUtils.isNotEmpty(reqMain)) {
                    for (SysInterfaceDict sysInterfaceDict : allSysInterfaceDict) {
                        try {
                            String webUrl = "";
                            if (sysInterfaceDict.getWebUrl().startsWith("http:")) {
                                webUrl = sysInterfaceDict.getWebUrl() + "/" + sysInterfaceDict.getCode();
                            } else {
                                webUrl = "http://" + sysInterfaceDict.getWebUrl() + "/" + sysInterfaceDict.getCode();
                            }
                            JSONObject q = new JSONObject();
                            q.set("reqNo", reqno);
                            q.set("username", sysUser.getUsername());
                            q.set("realname", sysUser.getRealname());
                            String returnMsg1 = HttpUtil.createPost(webUrl).body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().body();
                            JSONObject reportObject = JSONUtil.parseObj(returnMsg1);
                            logger.info(returnMsg1);
                            JSONObject reportStatus = reportObject.getJSONObject("status");
                            String reportCode = reportStatus.get("code").toString();
                            if ("400".equals(reportCode)) {
                                return Result.fail("接口管理平台异常,请检查");
                            }
                        } catch (Exception e) {
                            logger.info("接口方法异常：" + sysInterfaceDict.getType());
                        }
                    }
                }
            } catch (Exception e) {
                logger.info("开始上机接口异常，请核实！");
                e.printStackTrace();
            }

            return Result.succ(1, "扫码上机成功", labMainInfoServiceBak.getMainInfoById(labMaininfo.getId()));
        } else {
            return Result.fail("扫码上机失败！");
        }
    }

    private List<String> getListValueMethod(String value) {
        // 去掉首尾的方括号
        String str = value.replaceAll("\\[|\\]", "");
        // 分割字符串
        String[] parts = str.split(",");
        // 创建一个列表来存储整数
        List<String> list = new ArrayList<>();
        // 遍历分割后的字符串数组，并将其转换为整数后添加到列表中
        for (String part : parts) {
            // 去掉引号
            String numStr = part.trim().replaceAll("\"", "");
            list.add(numStr);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertMaininfoBySpecimen(AddLabMaininfo labReqMain) throws JsonProcessingException {
        String reqno = labReqMain.getReqNo();
        long l = System.currentTimeMillis();

        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(LabReqMain.class).selectAs(LabSampleType::getSampleTypeName, LabReqMain::getSampleTypeNa).eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, reqno).leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabReqMain::getSampleType);

        LabReqMain reqMain = labReqMainMapper.selectOne(queryWrapper);
        if (reqMain == null) {
            try {
                Result rsult = labMainInfoServiceBak.getApiReqMainInfo(labReqMain);
                if ("400".equals(rsult.getStatus().get("code") + "")) {
                    throw new RuntimeException(rsult.getStatus().get("msg") + "");
                }
            } catch (Exception e) {
                throw e;
            }

            reqMain = labMainInfoServiceBak.getLabReqMainEntity(reqno);//labReqMainMapper.selectOne(queryWrapper);'
        }
        return Result.succ(200, "有数据，同步成功", null);
    }

    /**
     * 通过时间毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    /**
     * Timestamp -> Date
     *
     * @param timestamp 时间戳
     * @return
     * @author whx
     * @date
     */
    public Date timeToDate(Timestamp timestamp) {

        // Timestamp -> String
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(timestamp);

        // String -> Date
        Date date = new Date();
        //注意format的格式要与日期String的格式相匹配
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    @Override
    public Result updateMaininfo(LabMaininfoCreateOrUpdateDto input) throws JsonProcessingException {
        return labMainInfoServiceBak.updateMaininfoController(input, 1);
    }

    @Override
    public Result updateMaininfoByScanReqNo(LabMaininfoCreateOrUpdateDto input) throws JsonProcessingException {
        return labMainInfoServiceBak.updateMaininfoController(input, 2);
    }

    @Override
    public Result updateBacMaininfo(LabMaininfo labMaininfo) {
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getId, labMaininfo.getId());
        Integer count = labMaininfoMapper.selectCount(queryWrapper);

        if (StringUtils.isNotBlank(labMaininfo.getPatNa())) {
            String apply = PinYinUtil.firstPinYinFun.apply(labMaininfo.getPatNa());
            labMaininfo.setPatPyName(apply);
        }
        //申请信息
        LabReqMain rmEntry = null;
        if (!BeanUtil.isEmpty(labMaininfo.getReqNo())) {
            LambdaQueryWrapper<LabReqMain> queryRMWrapper = new LambdaQueryWrapper<>();
            queryRMWrapper.eq(LabReqMain::getDelFlag, 0);
            queryRMWrapper.eq(LabReqMain::getReqNo, labMaininfo.getReqNo());

            List<LabReqMain> rmList = labReqMainMapper.selectList(queryRMWrapper);
            if (!rmList.isEmpty()) {
                rmEntry = rmList.get(0);
            }
        }

        if (count == 0) {
            labMaininfo.setTestTime(new Timestamp(System.currentTimeMillis()));
            SysUser sysUser = RedisUserManager.getUser();
            labMaininfo.setTestDoctor(sysUser.getUsername());
            labMaininfo.setOrgId(sysUser.getOrgId());
            if (BeanUtil.isEmpty(labMaininfo.getIsChk())) {
                labMaininfo.setIsChk(new BigDecimal(0));
            }

            if (!BeanUtil.isEmpty(rmEntry)) {
                BeanUtil.copyProperties(rmEntry, labMaininfo, "id", "isPrint");
            }

            //int i = labMaininfoMapper.insert(labMaininfo);


            //改修改
            LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
            lambdaQueryWrappers.eq(LabMaininfo::getSampleNo, labMaininfo.getSampleNo()).eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup()).eq(LabMaininfo::getSampleda, labMaininfo.getSampleda()).eq(LabMaininfo::getDelFlag, 0);
            boolean b = labMaininfoService.saveOrUpdate(labMaininfo, lambdaQueryWrappers);


            if (b) {
                LabReqMain finalRmEntry = rmEntry;
                /*标本流程状态记录*/
                new Thread(() -> {
                    //上机之后插入状态信息
                    LabMainState reqState1 = new LabMainState();
                    reqState1.setMaininfoId(labMaininfo.getId());
                    reqState1.setStateCode("90");
                    reqState1.setStateValue("微生物标本上机");
                    labMainStateService.save(reqState1);

                    /*插入状态*/
                    if (BeanUtil.isNotEmpty(finalRmEntry)) {
                        LabReqState reqState = new LabReqState();
                        reqState.setReqMainId(BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getId() : "");
                        reqState.setSampleda(labMaininfo.getSampleda());
                        reqState.setSampleNo(labMaininfo.getSampleNo());
                        reqState.setRptGroup(labMaininfo.getRptGroup());
                        reqState.setReqNo(BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getReqNo() : "");
                        reqState.setOrgId(labMaininfo.getOrgId());
                        reqState.setCreator(sysUser.getId());
                        reqState.setStateCode("90");
                        reqState.setStateValue("微生物标本上机");
                        String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "检验上机,标本号:" + (BeanUtil.isNotEmpty(finalRmEntry) ? finalRmEntry.getReqNo() : "");
                        reqState.setRemark(rmk);
                        reqState.setSeq(labReqStateService.getMaxCount(labMaininfo.getReqNo()));
                        labReqStateService.save(reqState);

                        if (BeanUtil.isNotEmpty(finalRmEntry)) {
                            finalRmEntry.setState("90");
                            finalRmEntry.setStateNa("微生物标本上机");
                            labReqMainService.saveOrUpdate(finalRmEntry);
                        }
                    }
                }).start();

                return Result.succ(1, "插入数据成功", labMainInfoServiceBak.getMainInfoById(labMaininfo.getId()));
            } else {
                return Result.fail("插入数据失败！");
            }
        } else {
            if (!BeanUtil.isEmpty(rmEntry)) {
                if ((!BeanUtil.isEmpty(rmEntry.getPatNo()) && BeanUtil.isEmpty(labMaininfo.getPatNo()) || (!BeanUtil.isEmpty(rmEntry.getPatNa()) && BeanUtil.isEmpty(labMaininfo.getPatNa())))) {
                    BeanUtil.copyProperties(rmEntry, labMaininfo, "id", "isPrint");
                }
            }

            int i = labMaininfoMapper.updateById(labMaininfo);

            if (i > 0) {
                return Result.succ(1, "修改据成功", labMainInfoServiceBak.getMainInfoById(labMaininfo.getId()));
            } else {
                return Result.fail("修改数据失败！");
            }
        }
    }

    @Override
    public Result deleteMaininfoById(LabMaininfo labMaininfo) {
        if (ToolsUtils.isNotEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().intValue() > 0) {
            return Result.fail("已审核不允许删除！");
        }
        int i = labMaininfoMapper.deleteById(labMaininfo.getId());
        //删除细项
        LambdaQueryWrapper<LabRptresult> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper1.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
        Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp timestamp1 = new Timestamp(labMaininfo.getSampleda().getTime());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate1 = sdf1.format(timestamp1);
        Timestamp endTime = Timestamp.valueOf(formattedDate1 + " 23:59:59");
        lambdaQueryWrapper1.ge(LabRptresult::getSampleda, startTime);
        lambdaQueryWrapper1.le(LabRptresult::getSampleda, endTime);
        labRptresultMapper.delete(lambdaQueryWrapper1);

        //删除图片
        LambdaQueryWrapper<LabRptresultImage> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(LabRptresultImage::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper2.eq(LabRptresultImage::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper2.ge(LabRptresultImage::getSampleda, startTime);
        lambdaQueryWrapper2.le(LabRptresultImage::getSampleda, endTime);
        labRptresultImageMapper.delete(lambdaQueryWrapper2);

        try {
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                LabMainState reqState1 = new LabMainState();
                reqState1.setMaininfoId(labMaininfo.getId());
                reqState1.setStateCode("9000");
                reqState1.setStateValue("删除上机记录");
                reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】" + "由" + sysUser.getRealname() + "删除上机记录");
                labMainStateService.save(reqState1);
            }).start();

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (i > 0) {
            return Result.succ(1, "删除数据成功", "");
        } else {
            return Result.fail("删除数据失败！");
        }

    }

    @Override
    public Result findRptResultByLabMaininfo(String id) {
        if (StringUtils.isEmpty(id)) {
            return Result.succ(1, "id为空", "");
        }
        LambdaQueryWrapper<LabMaininfo> queryMI = new LambdaQueryWrapper<>();
        queryMI.eq(LabMaininfo::getDelFlag, 0);
        queryMI.eq(LabMaininfo::getId, id);
        LabMaininfo miEntry = labMaininfoMapper.selectOne(queryMI);
        if (BeanUtil.isEmpty(miEntry)) {
            return Result.succ(1, "查无上机记录", "");
        }

        MPJLambdaWrapper<LabRptresult> queryWrapper = new MPJLambdaWrapper<>();
        //queryWrapper.eq(LabRptresult::getDelFlag, 0).eq(LabRptresult::getMaininfoId, id);
        //queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.distinct().selectAll(LabRptresult.class);
        queryWrapper.selectAs("instr", LabInstrSetup::getInstrName, LabRptresult::getInstrNa);
        queryWrapper.selectAs("dict", LabItemDict::getUnit, LabRptresult::getItemUnit);
        queryWrapper.selectAs("dict", LabItemDict::getSeq, LabRptresult::getDisplayOrder);
        queryWrapper.selectAs("dict", LabItemDict::getIsCalcItem, LabRptresult::getIsCalcItem);
        queryWrapper.selectAs("dict", LabItemDict::getId, LabRptresult::getItemDictId);
        queryWrapper.leftJoin(LabItemDict.class, "dict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
        queryWrapper.leftJoin(LabInstrSetup.class, "instr", p -> p.eq(LabInstrSetup::getRptGroup, LabRptresult::getRptGroup).eq(LabInstrSetup::getInstrCode, LabRptresult::getInstrCode).eq(LabInstrSetup::getDelFlag, 0));

        queryWrapper.eq(LabRptresult::getDelFlag, 0);
        Timestamp timestamp = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp timestamp1 = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate1 = sdf1.format(timestamp1);
        Timestamp endTime = Timestamp.valueOf(formattedDate1 + " 23:59:59");
        queryWrapper.ge(LabRptresult::getSampleda, startTime);
        queryWrapper.le(LabRptresult::getSampleda, endTime);
        queryWrapper.eq(LabRptresult::getRptGroup, miEntry.getRptGroup());
        queryWrapper.eq(LabRptresult::getSampleNo, miEntry.getSampleNo());
        queryWrapper.orderByAsc(LabItemDict::getSeq);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(queryWrapper);

        if (!labRptresults.isEmpty()) {

            List<String> list = labRptresults.stream().map(p -> p.getItemNo()).collect(Collectors.toList());

            List<LabFeeitemVsItemDict> labFeeitemVsItemDicts = labFeeitemVsItemDictMapper.selectList(
                    new LambdaQueryWrapper<LabFeeitemVsItemDict>().in(LabFeeitemVsItemDict::getItemNo, list)
                            .eq(LabFeeitemVsItemDict::getRptGroup, miEntry.getRptGroup()).eq(LabFeeitemVsItemDict::getDelFlag, 0));

            for (LabRptresult rptresult : labRptresults) {
                if (rptresult.getIsCalcItem() != null && rptresult.getIsCalcItem() == 1) {
                    rptresult.setIsContrast(1);
                    continue;
                }
                LabFeeitemVsItemDict labFeeitemVsItemDict = labFeeitemVsItemDicts.stream().filter(a -> a.getItemNo().equals(rptresult.getItemNo())).findFirst().orElse(null);
                if (labFeeitemVsItemDict != null) {
                    rptresult.setIsContrast(1);
                } else {
                    rptresult.setIsContrast(0);
                }
            }
            List<LabRptresult> collect = labRptresults.stream().filter(a -> StringUtils.isBlank(a.getMaininfoId())).collect(Collectors.toList());
            for (LabRptresult m : collect) {
                m.setMaininfoId(miEntry.getId());
            }
            labRptresultService.updateBatchById(collect);
        }
        return Result.succ(1, "查询结果成功", labRptresults);
    }

    @Override
    public Result findLabMaininfo(LabMaininfo labMaininfo) {
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        SysUser sysUser = RedisUserManager.getUser();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        queryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        queryWrapper.selectAs("test", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        queryWrapper.selectAs("chk", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        queryWrapper.selectAs("rechk", SysUser::getRealname, LabMaininfo::getReChkDoctorNa);
        queryWrapper.selectAs("prt", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("sampl", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        queryWrapper.selectAs("signer", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.selectAs("reqm", LabReqMainQuery::getId, LabMaininfo::getReqMainId);
        queryWrapper.selectAs("reqm", LabReqMainQuery::getPatId, LabMaininfo::getPatId);
        queryWrapper.leftJoin(LabSampleType.class, p -> p.eq(LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType).eq(LabSampleType::getDelFlag, 0));
        queryWrapper.leftJoin(SysOrgDepartment.class, p -> p.eq(SysOrgDepartment::getCode, LabMaininfo::getReqDept).eq(SysOrgDepartment::getDelFlag, 0));
        queryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "test", p -> p.eq(SysUser::getUsername, LabMaininfo::getTestDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "chk", p -> p.eq(SysUser::getUsername, LabMaininfo::getChkDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "rechk", p -> p.eq(SysUser::getUsername, LabMaininfo::getReChkDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "prt", p -> p.eq(SysUser::getUsername, LabMaininfo::getPrintDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "sampl", p -> p.eq(SysUser::getUsername, LabMaininfo::getSamplingDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "signer", p -> p.eq(SysUser::getUsername, LabMaininfo::getSignerDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(LabRptGroup.class, "rptgrp", p -> p.eq(LabRptGroup::getRptGroup, LabMaininfo::getRptGroup).eq(LabRptGroup::getDelFlag, 0));
        queryWrapper.leftJoin(LabReqMainQuery.class, "reqm", p -> p.eq(LabReqMainQuery::getReqNo, LabMaininfo::getReqNo).eq(LabReqMainQuery::getDelFlag, 0));
        if (ToolsUtils.isNotEmpty(sysUser)) {
            queryWrapper.eq(Objects.nonNull(sysUser), LabMaininfo::getOrgId, sysUser.getOrgId());
        }
        queryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getId()), LabMaininfo::getId, labMaininfo.getId());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getPatType()), LabMaininfo::getPatType, labMaininfo.getPatType());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getSampleNo()), LabMaininfo::getSampleNo, labMaininfo.getSampleNo());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getSampleType()), LabMaininfo::getSampleType, labMaininfo.getSampleType());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getReqPurposeId()), LabReqMainQuery::getPurposeNo, labMaininfo.getReqPurposeId());
        queryWrapper.like(StringUtils.isNotBlank(labMaininfo.getPatNa()), LabMaininfo::getPatNa, labMaininfo.getPatNa());
        //是否是从筛选中查询
        if (null != labMaininfo.getIsFilter() && labMaininfo.getIsFilter()) {
            //是否选中查询当天
            if (Objects.nonNull(labMaininfo.getQueryDay())) {
                // 获取当前时间
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, -labMaininfo.getQueryDay()); // 减去对应天数
                // 设置到当天的开始时间
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                Timestamp startOfDay = new Timestamp(calendar.getTimeInMillis());

                // 设置到当天的结束时间
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);
                Timestamp endOfDay = new Timestamp(calendar.getTimeInMillis());
                queryWrapper.ge(LabMaininfo::getSampleda, startOfDay);
                queryWrapper.le(LabMaininfo::getSampleda, endOfDay);
            } else {
                if (StringUtils.isNotBlank(labMaininfo.getTestTimeS())) {
                    Timestamp testTimeS = Timestamp.valueOf(labMaininfo.getTestTimeS() + " 00:00:00");
                    queryWrapper.ge(LabMaininfo::getSampleda, testTimeS);
                }
                if (StringUtils.isNotBlank(labMaininfo.getTestTimeE())) {
                    Timestamp testTimeE = Timestamp.valueOf(labMaininfo.getTestTimeE() + " 23:59:59");
                    queryWrapper.le(LabMaininfo::getSampleda, testTimeE);
                }
                if (StringUtils.isNotBlank(labMaininfo.getChkTimeS())) {
                    Timestamp chkTimeS = Timestamp.valueOf(labMaininfo.getChkTimeS() + " 00:00:00");
                    queryWrapper.ge(LabMaininfo::getChkTime, chkTimeS);
                }
                if (StringUtils.isNotBlank(labMaininfo.getChkTimeE())) {
                    Timestamp chkTimeE = Timestamp.valueOf(labMaininfo.getChkTimeE() + " 23:59:59");
                    queryWrapper.le(LabMaininfo::getChkTime, chkTimeE);
                }
            }
        } else {
            Timestamp startTime = Timestamp.valueOf(labMaininfo.getSampleDaStr() + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(labMaininfo.getSampleDaStr() + " 23:59:59");
            queryWrapper.ge(LabMaininfo::getSampleda, startTime);
            queryWrapper.le(LabMaininfo::getSampleda, endTime);
        }


        /*快速查询条件*/
        if (!BeanUtil.isEmpty(labMaininfo.getStateCode())) {
            switch (labMaininfo.getStateCode()) {
                case 1://已审核
                    queryWrapper.eq(LabMaininfo::getIsChk, 2);
                    break;
                case 2://未审核
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().isNull(LabMaininfo::getIsChk));
                    break;
                case 3://已初审
                    queryWrapper.eq(LabMaininfo::getIsChk, 1);
                    break;
                case 4: //已打印
                    queryWrapper.eq(LabMaininfo::getIsPrint, 1);
                    break;
                case 5://未打印
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
                    break;
                case 6://已审核已打印
                    queryWrapper.eq(LabMaininfo::getIsChk, 2);
                    queryWrapper.eq(LabMaininfo::getIsPrint, 1);
                    break;
                case 7://已审核未打印
                    queryWrapper.eq(LabMaininfo::getIsChk, 2);
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
                    break;
                case 8://未审核已打印
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().isNull(LabMaininfo::getIsChk));
                    queryWrapper.eq(LabMaininfo::getIsPrint, 1);
                    break;
                case 9://未审核未打印
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().isNull(LabMaininfo::getIsChk));
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
                    break;
                case 10://初审已打印
                    queryWrapper.eq(LabMaininfo::getIsChk, 1);
                    queryWrapper.eq(LabMaininfo::getIsPrint, 1);
                    break;
                case 11://初审未打印
                    queryWrapper.eq(LabMaininfo::getIsChk, 1);
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
                    break;
            }
        }

        if (!BeanUtil.isEmpty(labMaininfo.getIsSelf())) {
            queryWrapper.and(p -> p.eq(LabMaininfo::getTestDoctor, sysUser.getUsername()).or().eq(LabMaininfo::getChkDoctor, sysUser.getUsername()));
        }

        queryWrapper.orderByAsc(LabMaininfo::getSampleNo);
        queryWrapper.orderByAsc(LabMaininfo::getSampleda);

        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);

        //获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabMaininfo maininfo : labMaininfos) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));

            }

        }
        return Result.succ(1, "查询成功", labMaininfos);
    }

    /*微生物获取上机记录*/
    @Override
    public Result findLabMaininfoBac(LabMaininfo labMaininfo) {
        return labMaininfoBacServiceImpl.findLabMaininfoBac(labMaininfo);
    }

    /*基础字典 显示文本 赋值*/
    private void baseDictDataAssign(List<LabMaininfo> maininfos) {
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabMaininfo maininfo : maininfos) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));

            }

        }
    }

    private LabMaininfo findLastLabMainInfo(LabMaininfo labMaininfo) {
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        SysUser sysUser = RedisUserManager.getUser();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        queryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        queryWrapper.selectAs("test", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        queryWrapper.selectAs("chk", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        queryWrapper.selectAs("rechk", SysUser::getRealname, LabMaininfo::getReChkDoctorNa);
        queryWrapper.selectAs("prt", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("sampl", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        queryWrapper.selectAs("signer", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType);
        queryWrapper.leftJoin(SysOrgDepartment.class, SysOrgDepartment::getCode, LabMaininfo::getReqDept);
        queryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "test", SysUser::getUsername, LabMaininfo::getTestDoctor);
        queryWrapper.leftJoin(SysUser.class, "chk", SysUser::getUsername, LabMaininfo::getChkDoctor);
        queryWrapper.leftJoin(SysUser.class, "rechk", SysUser::getUsername, LabMaininfo::getReChkDoctor);
        queryWrapper.leftJoin(SysUser.class, "prt", SysUser::getUsername, LabMaininfo::getPrintDoctor);
        queryWrapper.leftJoin(SysUser.class, "sampl", SysUser::getUsername, LabMaininfo::getSamplingDoctor);
        queryWrapper.leftJoin(SysUser.class, "signer", SysUser::getUsername, LabMaininfo::getSignerDoctor);
        queryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        if (ToolsUtils.isNotEmpty(sysUser)) {
            queryWrapper.eq(Objects.nonNull(sysUser), LabMaininfo::getOrgId, sysUser.getOrgId());
        }
        queryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getId()), LabMaininfo::getId, labMaininfo.getId());

        if (!BeanUtil.isEmpty(labMaininfo.getSampleDaStr())) {
            Timestamp startTime = Timestamp.valueOf(labMaininfo.getSampleDaStr() + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(labMaininfo.getSampleDaStr() + " 23:59:59");
            queryWrapper.ge(LabMaininfo::getSampleda, startTime);
            queryWrapper.le(LabMaininfo::getSampleda, endTime);
        }
        queryWrapper.orderByAsc(LabMaininfo::getSampleNo);
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);

        //获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabMaininfo maininfo : labMaininfos) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));

            }

        }
        return labMaininfos.get(0);
    }


    /**
     * 获取审批信息
     *
     * @param reviewedMaininfoDto
     * @return
     */
    @Override
    public Result findReviewedResutByLabMaininfo(ReviewedMaininfoDto reviewedMaininfoDto) {
        String customSorting = reviewedMaininfoDto.getCustomSorting();
        //LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        queryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
//        queryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
//        queryWrapper.selectAs("test", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
//        queryWrapper.selectAs("chk", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
//        queryWrapper.selectAs("rechk", SysUser::getRealname, LabMaininfo::getReChkDoctorNa);
//        queryWrapper.selectAs("prt", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
//        queryWrapper.selectAs("sampl", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
//        queryWrapper.selectAs("signer", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getSeq, LabMaininfo::getRptGroupSeq);
        queryWrapper.leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType);
        queryWrapper.leftJoin(SysOrgDepartment.class, SysOrgDepartment::getCode, LabMaininfo::getReqDept);
        queryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
//        queryWrapper.leftJoin(SysUser.class, "test", SysUser::getUsername, LabMaininfo::getTestDoctor);
//        queryWrapper.leftJoin(SysUser.class, "chk", SysUser::getUsername, LabMaininfo::getChkDoctor);
//        queryWrapper.leftJoin(SysUser.class, "rechk", SysUser::getUsername, LabMaininfo::getReChkDoctor);
//        queryWrapper.leftJoin(SysUser.class, "prt", SysUser::getUsername, LabMaininfo::getPrintDoctor);
//        queryWrapper.leftJoin(SysUser.class, "sampl", SysUser::getUsername, LabMaininfo::getSamplingDoctor);
//        queryWrapper.leftJoin(SysUser.class, "signer", SysUser::getUsername, LabMaininfo::getSignerDoctor);
        queryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);

        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(StringUtils.isNotEmpty(reviewedMaininfoDto.getOrgId()), LabMaininfo::getOrgId, reviewedMaininfoDto.getOrgId());
        queryWrapper.eq(StringUtils.isNotEmpty(reviewedMaininfoDto.getRptGroup()), LabMaininfo::getRptGroup, reviewedMaininfoDto.getRptGroup());
        //queryWrapper.eq(StringUtils.isNotEmpty(reviewedMaininfoDto.getSampleNo()), LabMaininfo::getSampleNo, reviewedMaininfoDto.getSampleNo());
        if (StringUtils.isNotEmpty(reviewedMaininfoDto.getScheduleDateBegin()) && StringUtils.isNotEmpty(reviewedMaininfoDto.getScheduleDateEnd())) {
            Timestamp startTime = Timestamp.valueOf(reviewedMaininfoDto.getScheduleDateBegin());
            Timestamp endTime = Timestamp.valueOf(reviewedMaininfoDto.getScheduleDateEnd());
            queryWrapper.ge(LabMaininfo::getSampleda, startTime);
            queryWrapper.le(LabMaininfo::getSampleda, endTime);
        }
        queryWrapper.in(CollectionUtils.isNotEmpty(reviewedMaininfoDto.getVisitTypeIds()), LabMaininfo::getPatType, reviewedMaininfoDto.getVisitTypeIds());
        queryWrapper.in(CollectionUtils.isNotEmpty(reviewedMaininfoDto.getTestDoctor()), LabMaininfo::getTestDoctor, reviewedMaininfoDto.getTestDoctor());
        queryWrapper.in(CollectionUtils.isNotEmpty(reviewedMaininfoDto.getReqDepts()), LabMaininfo::getReqDept, reviewedMaininfoDto.getReqDepts());
        queryWrapper.in(CollectionUtils.isNotEmpty(reviewedMaininfoDto.getReqWards()), LabMaininfo::getReqWard, reviewedMaininfoDto.getReqWards());
        queryWrapper.in(CollectionUtils.isNotEmpty(reviewedMaininfoDto.getSpecTypeIds()), LabMaininfo::getSampleType, reviewedMaininfoDto.getSpecTypeIds());
        if (null != reviewedMaininfoDto.getIsReviewed()) {
            if (reviewedMaininfoDto.getIsReviewed() == 0) {
                queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().eq(LabMaininfo::getIsChk, 1).or().isNull(LabMaininfo::getIsChk));
            } else {
                queryWrapper.eq(LabMaininfo::getIsChk, 2);
            }
        }
        if (null != reviewedMaininfoDto.getIsPrinted()) {
            if (reviewedMaininfoDto.getIsPrinted() == 0) {
                queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
            } else {
                queryWrapper.eq(LabMaininfo::getIsPrint, reviewedMaininfoDto.getIsPrinted());
            }
        }
        if (Objects.nonNull(reviewedMaininfoDto.getIsFilterNoPatName()) && reviewedMaininfoDto.getIsFilterNoPatName()) {
            queryWrapper.isNotNull(LabMaininfo::getPatNa);
        }

        if (Objects.nonNull(reviewedMaininfoDto.getIsFilterNoSpecCode()) && reviewedMaininfoDto.getIsFilterNoSpecCode()) {
            queryWrapper.isNotNull(LabMaininfo::getReqNo);
        }
        if (Objects.nonNull(reviewedMaininfoDto.getIsFilterNoResult()) && reviewedMaininfoDto.getIsFilterNoResult()) {
            queryWrapper.exists("SELECT 1 FROM LAB_RPTRESULT t2 WHERE t.id = t2.MAININFO_ID");
        }
        if (!StringUtils.isEmpty(reviewedMaininfoDto.getSampleNo())) {
            List<String> sampleNoList = getSampleNoList(reviewedMaininfoDto.getSampleNo());
            queryWrapper.in(LabMaininfo::getSampleNo, sampleNoList);
        }
        //queryWrapper.orderByDesc(LabRptGroup::getSeq).orderByAsc(LabMaininfo::getSampleda);//.orderByAsc(LabMaininfo::getRptGroup);

        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);
        sortLabMainInfo(labMaininfos);
        Comparator<LabMaininfo> comparator;
        //根据不同的条件排序
        if ("0".equals(customSorting)) {
            //comparator = Comparator.comparing(LabMaininfo::getSampleNo, Comparator.nullsLast(Comparator.naturalOrder()));
            comparator = Comparator.comparing(LabMaininfo::getRptGroupSeq, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleda, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSeqNo, Comparator.nullsLast(Comparator.naturalOrder()));
        } else if ("1".equals(customSorting)) {
            comparator = Comparator.comparing(LabMaininfo::getReqDept, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getBedNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleda, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSeqNo, Comparator.nullsLast(Comparator.naturalOrder()));
        } else if ("2".equals(customSorting)) {
            comparator = Comparator.comparing(LabMaininfo::getPatType, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getReqDept, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getBedNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleda, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSeqNo, Comparator.nullsLast(Comparator.naturalOrder()));
        } else if ("3".equals(customSorting)) {
            comparator = Comparator.comparing(LabMaininfo::getPatType, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getReqDept, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleda, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSeqNo, Comparator.nullsLast(Comparator.naturalOrder()));
        } else if ("4".equals(customSorting)) {
            comparator = Comparator.comparing(LabMaininfo::getReqDept, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleda, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSeqNo, Comparator.nullsLast(Comparator.naturalOrder()));
        } else {
            comparator = Comparator.comparing(LabMaininfo::getRptGroupSeq, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleda, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSeqNo, Comparator.nullsLast(Comparator.naturalOrder()));
        }

        List<LabMaininfo> collect = labMaininfos.stream().sorted(comparator).collect(Collectors.toList());

        baseDictDataAssign(collect);

        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getDelFlag, 0));
        collect.forEach(a -> {
            try {
                a.setReqDoctorNa(list.stream().filter(a1 -> a1.getUsername().equals(a.getReqDoctor())).findFirst().get().getRealname());
                a.setSignerDoctorNa(list.stream().filter(a1 -> a1.getUsername().equals(a.getSignerDoctor())).findFirst().get().getRealname());
                a.setPrintDoctorNa(list.stream().filter(a1 -> a1.getUsername().equals(a.getPrintDoctor())).findFirst().get().getRealname());
                a.setSamplingDoctorNa(list.stream().filter(a1 -> a1.getUsername().equals(a.getSamplingDoctor())).findFirst().get().getRealname());
                a.setTestDoctorNa(list.stream().filter(a1 -> a1.getUsername().equals(a.getTestDoctor())).findFirst().get().getRealname());
                a.setChkDoctorNa(list.stream().filter(a1 -> a1.getUsername().equals(a.getChkDoctor())).findFirst().get().getRealname());
                a.setReChkDoctorNa(list.stream().filter(a1 -> a1.getUsername().equals(a.getReChkDoctor())).findFirst().get().getRealname());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //工作组筛选条件需求不明确
        return Result.succ(1, "查询成功", collect);

    }

    private List<String> getSampleNoList(String sampleNo) {
        List<String> stringList = new ArrayList<>();
        String[] split = sampleNo.split(",");
        for (String sp : split) {
            boolean contains = sp.contains("-");
            if (contains) {
                String[] split1 = sp.split("-");
                boolean digits = NumberUtils.isDigits(split1[0]);
                boolean digits1 = NumberUtils.isDigits(split1[1]);
                if (digits && digits1) {
                    Integer f = Integer.valueOf(split1[0]);
                    Integer s = Integer.valueOf(split1[1]);
                    for (int i = f; i <= s; i++) {
                        stringList.add(String.valueOf(i));
                    }
                }
            } else {
                stringList.add(sp);
            }
        }
        return stringList.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public Result findInspectResultList(ReviewedMaininfoDto reviewedMaininfoDto) {
        Result reviewedResutByLabMaininfo = findReviewedResutByLabMaininfo(reviewedMaininfoDto);
        List<LabMaininfo> labMaininfos = (List<LabMaininfo>) reviewedResutByLabMaininfo.getData();
        List<LabRptresult> labRptresults = new ArrayList<>();
        if (labMaininfos.size() > 0) {
            List<String> ids = labMaininfos.stream().map(labMaininfo -> labMaininfo.getId()).collect(Collectors.toList());
            MPJLambdaWrapper<LabRptresult> lambdaQueryWrapper = new MPJLambdaWrapper<>();
            lambdaQueryWrapper.selectAll(LabRptresult.class);
            lambdaQueryWrapper.selectAs(LabMaininfo::getSampleda, LabRptresult::getSampleda);
            lambdaQueryWrapper.selectAs(LabMaininfo::getSampleNo, LabRptresult::getSampleNo);
            lambdaQueryWrapper.selectAs(LabMaininfo::getRptGroup, LabRptresult::getRptGroup);

            lambdaQueryWrapper.eq(LabRptresult::getDelFlag, 0).eq(StrUtil.isNotEmpty(reviewedMaininfoDto.getItemDictId()), LabRptresult::getItemNo, reviewedMaininfoDto.getItemDictId()).in(LabRptresult::getMaininfoId, ids);

            lambdaQueryWrapper.leftJoin(LabMaininfo.class, "minfo", LabMaininfo::getId, LabRptresult::getMaininfoId);
            lambdaQueryWrapper.orderByAsc(LabRptresult::getDisplayOrder);
            labRptresults = labRptresultMapper.selectList(lambdaQueryWrapper);
        }

        return Result.succ(1, "查询成功！", labRptresults);
    }

    /**
     * 批量更新调整结果
     *
     * @param updateTestResultParams
     * @return
     */
    @Override
    public Result saveTestResultBatch(UpdateTestResultParams updateTestResultParams) {
        SysUser sysUser = RedisUserManager.getUser();
        String formulae = updateTestResultParams.getFormulae();
        if (updateTestResultParams.getNeedFormulae()) {
            Assert.isTrue(formulae.contains("R"), "公式不含有'R'字符，公式错误！");
        }
        List<LabRptresult> LabRptresults = new ArrayList<>();
        List<LabResultAmendment> labResultAmendments = new ArrayList<>();
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        Optional.ofNullable(updateTestResultParams.getInspectResults()).ifPresent(testResultParams -> testResultParams.stream().filter(item -> ObjectUtil.isNotEmpty(item.getTestResult())).forEach(inspectResultDto -> {
            LabRptresult labRptresult = new LabRptresult();
            //BeanUtil.copyProperties(inspectResultDto, labRptresult);
            if (updateTestResultParams.getNeedFormulae()) {
                String expression = formulae.replace("R", inspectResultDto.getTestResult());
                Object result;
                try {
                    result = engine.eval(expression);
                } catch (ScriptException e) {
                    throw new RuntimeException(e);
                }

                labRptresult.setTestResult(result.toString());
            } else {
                labRptresult.setTestResult(String.format("%.2f", Double.parseDouble(inspectResultDto.getTestResult()) * Double.parseDouble(updateTestResultParams.getRatio()) + Double.parseDouble(updateTestResultParams.getStep())));
            }
            //labRptresult.setAdjustResult(inspectResultDto.getTestResult());
            labRptresult.setId(inspectResultDto.getId());
            labRptresult.setMaininfoId(inspectResultDto.getMaininfoId());
            LabRptresults.add(labRptresult);

            LabResultAmendment labResultAmendment = new LabResultAmendment();
            labResultAmendment.setMaininfoId(inspectResultDto.getMaininfoId());
            labResultAmendment.setWlResult(labRptresult.getId());
            labResultAmendment.setItemNa(labRptresult.getItemNa());
            labResultAmendment.setItemNo(labRptresult.getItemNo());
            labResultAmendment.setOriginalResult(inspectResultDto.getTestResult());
            labResultAmendment.setAmendedResult(labRptresult.getTestResult());
            labResultAmendment.setAmendedDate(new Timestamp(new Date().getTime()));
            labResultAmendment.setAmendedReason(updateTestResultParams.getAmendedReason());
            labResultAmendment.setAmendedUserId(ObjectUtil.isNotEmpty(sysUser) ? sysUser.getId() : "");
            labResultAmendment.setAmendedUserName(ObjectUtil.isNotEmpty(sysUser) ? sysUser.getRealname() : "");
            labResultAmendments.add(labResultAmendment);
        }));
        // 批量更新
        labRptresultService.updateBatchById(LabRptresults);
        // 批量插入数据
        labResultAmendmentService.saveBatch(labResultAmendments);

        //重新计算参考范围等
        List<String> ids = LabRptresults.stream().map(LabRptresult::getMaininfoId).collect(Collectors.toList());
        if (!ids.isEmpty()) {
            MPJLambdaWrapper<LabMaininfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
            lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
            lambdaQueryWrapper.in(LabMaininfo::getId, ids);
            List<LabMaininfo> lst = labMaininfoMapper.selectList(lambdaQueryWrapper);
            labRptresultService.reCalcRptRssultsMany(lst);
        }
        return Result.succ(1, "保存成功1", "");
    }

    @Override
    public Result updateBacTestChkDoctorAfterAuth(UptMainInfoTextChkDoctorDto input) {
        UptedLabMainInfo res = new UptedLabMainInfo();
        LambdaUpdateWrapper<LabMaininfo> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(LabMaininfo::getId, BeanUtil.isEmpty(input.getId()) ? "!@#$%" : input.getId());
        LabMaininfo labMaininfo = null;//labMaininfoMapper.selectOne(queryWrapper);
        if (!BeanUtil.isEmpty(input.getId())) {
            labMaininfo = labMaininfoServiceExtend.getLabMaininfoById(ToolsUtils.isEmpty(input.getId()) ? "!@#$%" : input.getId()); //labMaininfoMapper.selectOne(queryWrapper);
        }

        /*初审*/
        if (input.getAction().equals("1") && !BeanUtil.isEmpty(labMaininfo)) {
            if (BeanUtil.isEmpty(input.getActerCode())) {
                return Result.fail("审核人编码为空");
            }
            if (BeanUtil.isEmpty(input.getActerNa())) {
                return Result.fail("审核人姓名为空");
            }
            labMaininfo.setChkDoctor(input.getActerCode());
            labMaininfo.setChkDoctorNa(input.getActerNa());
            labMaininfo.setIsChk(new BigDecimal(1));
            labMaininfo.setChkTime(new Timestamp(System.currentTimeMillis()));
            /*走审核逻辑*/

            try {
                labMaininfo = chkBacMainInfo(labMaininfo);
                if (StrUtil.isNotEmpty(labMaininfo.getMsg())) {
                    throw new RuntimeException(labMaininfo.getMsg());
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            res.setCurMainInfo(labMaininfo);
        }
        /*审核*/
        if (input.getAction().equals("2") && !BeanUtil.isEmpty(labMaininfo)) {
            if (BeanUtil.isEmpty(input.getActerCode())) {
                return Result.fail("审核人编码为空");
            }
            if (BeanUtil.isEmpty(input.getActerNa())) {
                return Result.fail("审核人姓名为空");
            }
            //专家智能规则库校验
            Boolean aBoolean = bacRuleService.checkProcessRule(labMaininfo, "1");
            if (aBoolean) {
                return Result.fail("专家智能规则库校验未通过");
            }

            labMaininfo.setChkDoctor(input.getActerCode());
            labMaininfo.setChkDoctorNa(input.getActerNa());
            labMaininfo.setIsChk(new BigDecimal(2));

            try {
                /*取消审核时保留审核时间   qxshsblshsj*/
                SysParamParam qxshsblshsj = new SysParamParam();
                qxshsblshsj.setParamCode("bgdyxtcs");
                qxshsblshsj.setField("qxshsblshsj");
                qxshsblshsj.setClassifyCode(labMaininfo.getRptGroup());
                List<SysParamFieldValueDto> qxshsblshsjLst = sysParamValueService.findSysParamFieldAndValueListByCode(qxshsblshsj);
                logger.info("qxshsblshsjLst:" + qxshsblshsjLst);
                String qxshsblshsjStr = qxshsblshsjLst.get(0).getValue();

                /*审核时保留原始非空审核时间   shsblysfkshsj*/
                SysParamParam shsblysfkshsj = new SysParamParam();
                shsblysfkshsj.setParamCode("bgdyxtcs");
                shsblysfkshsj.setField("shsblysfkshsj");
                shsblysfkshsj.setClassifyCode(labMaininfo.getRptGroup());
                List<SysParamFieldValueDto> shsblysfkshsjLst = sysParamValueService.findSysParamFieldAndValueListByCode(shsblysfkshsj);
                logger.info("shsblysfkshsjLst:" + shsblysfkshsj);
                String shsblysfkshsjStr = shsblysfkshsjLst.get(0).getValue();

                if (StringUtils.isNotEmpty(qxshsblshsjStr) && qxshsblshsjStr.equals("1") && StringUtils.isNotEmpty(shsblysfkshsjStr) && shsblysfkshsjStr.equals("1") && !BeanUtil.isEmpty(labMaininfo.getChkTime())) {
                    //保留原始非空审核时间，不做处理
                } else {
                    labMaininfo.setChkTime(new Timestamp(System.currentTimeMillis()));
                }
            } catch (Exception e) {
                logger.info("取消审核时保留审核时间   qxshsblshsj异常：" + e.getMessage());
                labMaininfo.setChkTime(new Timestamp(System.currentTimeMillis()));
            }

            /*走审核逻辑*/
            try {
                labMaininfo = chkBacMainInfo(labMaininfo);
                if (StrUtil.isNotEmpty(labMaininfo.getMsg())) {
                    throw new RuntimeException(labMaininfo.getMsg());
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            getIsAddFee(labMaininfo);
            res.setCurMainInfo(labMaininfo);
        }

        if (input.getAction().equals("3") && !BeanUtil.isEmpty(labMaininfo)) {
            if (BeanUtil.isEmpty(input.getActerCode())) {
                return Result.fail("审核人编码为空");
            }
            if (BeanUtil.isEmpty(input.getActerNa())) {
                return Result.fail("审核人姓名为空");
            }
            labMaininfo.setTestDoctor(input.getActerCode());
            labMaininfo.setTestDoctorNa(input.getActerNa());
            labMaininfoMapper.updateById(labMaininfo);
            res.setCurMainInfo(labMaininfo);
        }

        if (input.getAction().equals("4") && !BeanUtil.isEmpty(labMaininfo)) {
            if (BeanUtil.isEmpty(input.getActerCode())) {
                return Result.fail("审核人编码为空");
            }
            if (BeanUtil.isEmpty(input.getActerNa())) {
                return Result.fail("审核人姓名为空");
            }
            labMaininfo.setChkDoctor(input.getActerCode());
            labMaininfo.setChkDoctorNa(input.getActerNa());
            labMaininfoMapper.updateById(labMaininfo);
            res.setCurMainInfo(labMaininfo);
        }
        return Result.succ(1, "更新成功", res);
    }

    private void getIsAddFee(LabMaininfo labMaininfo) {
        Timestamp sampleda = labMaininfo.getSampleda();
        String rptGroup = labMaininfo.getRptGroup();
        String sampleNo = labMaininfo.getSampleNo();
        LambdaQueryWrapper<BacDrugTestResult> queryWrapperMR = new LambdaQueryWrapper<>();
        queryWrapperMR.eq(BacDrugTestResult::getDelFlag, 0)
                .eq(BacDrugTestResult::getSampleNo, sampleNo)
                .eq(BacDrugTestResult::getRptGroup, rptGroup);
        if (!BeanUtil.isEmpty(sampleda)) {
            Timestamp startTime = Timestamp.valueOf(sampleda.toString().substring(0, 10) + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(sampleda.toString().substring(0, 10) + " 23:59:59");
            queryWrapperMR.ge(BacDrugTestResult::getSampleda, startTime);
            queryWrapperMR.le(BacDrugTestResult::getSampleda, endTime);
        }
        Integer rPlanCnt = bacDrugTestResultMapper.selectCount(queryWrapperMR);
        if (rPlanCnt > 0) {
            LambdaQueryWrapper<BacAddFee> queryWrapperFee = new LambdaQueryWrapper<>();
            queryWrapperFee.eq(BacAddFee::getDelFlag, 0)
                    .eq(BacAddFee::getSampleNo, sampleNo)
                    .eq(BacAddFee::getRptGroup, rptGroup);
            if (!BeanUtil.isEmpty(sampleda)) {
                Timestamp startTime = Timestamp.valueOf(sampleda.toString().substring(0, 10) + " 00:00:00");
                Timestamp endTime = Timestamp.valueOf(sampleda.toString().substring(0, 10) + " 23:59:59");
                queryWrapperFee.ge(BacAddFee::getSampleda, startTime);
                queryWrapperFee.le(BacAddFee::getSampleda, endTime);
            }
            Integer feeCnt = bacAddFeeMapper.selectCount(queryWrapperFee);
            if (feeCnt > 0) {
                labMaininfo.setAddFee(0);
            } else {
                labMaininfo.setAddFee(1);
            }
        }
    }

    @Autowired
    BacAddFeeMapper bacAddFeeMapper;

    @Override
    public Result unChkBacMainInfo(LabMaininfo labMaininfo) throws JsonProcessingException {
        LabMaininfo mainInfo = findLastLabMainInfo(labMaininfo);
        if (BeanUtil.isEmpty(mainInfo.getIsChk()) || mainInfo.getIsChk().equals(new BigDecimal(0))) {
            return Result.succ(mainInfo);
        }
        if (!BeanUtil.isEmpty(mainInfo.getIsChk()) && mainInfo.getIsChk().equals(new BigDecimal(1))) {
            //取消初审
            mainInfo.setIsChk(new BigDecimal(0));
            mainInfo.setUnchkTime(new Timestamp(System.currentTimeMillis()));
            this.updateBacMaininfo(mainInfo);
            //添加状态记录
            LabMainState reqState1 = new LabMainState();
            reqState1.setMaininfoId(mainInfo.getId());
            reqState1.setStateCode("140");//mainInfo.getIsChk().toString());
            String txt = "取消初审";
            reqState1.setStateValue(txt);
            if (BeanUtil.isEmpty(labMaininfo.getUnChkDoctor())) {
                SysUser sysUser = RedisUserManager.getUser();
                reqState1.setCreator(sysUser.getId());
                reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + txt);
            } else {
                reqState1.setCreator(labMaininfo.getUnChkDoctor());
                reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + labMaininfo.getUnChkDoctorNa() + "," + txt);
            }
            labMainStateService.save(reqState1);
        }
        if (!BeanUtil.isEmpty(mainInfo.getIsChk()) && mainInfo.getIsChk().equals(new BigDecimal(2))) {
            /*标本审核后超过____分钟禁止取消审核 */
            SysParamParam sysp1 = new SysParamParam();
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("cgfzsjzsh");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if (!BeanUtil.isEmpty(r1.get(0).getValue()) && !BeanUtil.isEmpty(mainInfo.getChkTime())) {
                    try {
                        //Timestamp endTime = Timestamp.valueOf(labMaininfo.getSampleDaStr() + " 23:59:59");
                        int minute = Integer.parseInt(r1.get(0).getValue());
                        DateTime lastAllowDate = DateUtil.offsetMinute(mainInfo.getChkTime(), minute);
                        DateTime currDateTime = DateUtil.offsetMinute(new Timestamp(System.currentTimeMillis()), 0);

                        if (currDateTime.compareTo(lastAllowDate) > 0) {
                            //return Result.fail("标本审核后超过" + minute + "分钟禁止取消审核");
                        }
                    } catch (Exception e) {
                        //TODO
                    }
                }
            }
            //取消审核
            mainInfo.setIsChk(new BigDecimal(0));
            try {
                /*取消审核时保留审核时间   qxshsblshsj*/
                SysParamParam qxshsblshsj = new SysParamParam();
                qxshsblshsj.setParamCode("bgdyxtcs");
                qxshsblshsj.setField("qxshsblshsj");
                qxshsblshsj.setClassifyCode(mainInfo.getRptGroup());
                List<SysParamFieldValueDto> qxshsblshsjLst = sysParamValueService.findSysParamFieldAndValueListByCode(qxshsblshsj);
                if (ToolsUtils.isNotEmpty(qxshsblshsjLst)) {
                    String qxshsblshsjStr = qxshsblshsjLst.get(0).getValue();
                    if (StringUtils.isEmpty(qxshsblshsjStr) || !qxshsblshsjStr.equals("1")) {
                        mainInfo.setChkTime(null);
                    }
                }
            } catch (JsonProcessingException e) {
                mainInfo.setChkTime(null);
            }
            this.updateBacMaininfo(mainInfo);
            //添加状态记录
            LabMainState reqState1 = new LabMainState();
            reqState1.setMaininfoId(mainInfo.getId());
            reqState1.setStateCode("140");//mainInfo.getIsChk().toString());
            String txt = "取消审核";
            reqState1.setStateValue(txt);
            if (BeanUtil.isEmpty(labMaininfo.getUnChkDoctor())) {
                SysUser sysUser = RedisUserManager.getUser();
                reqState1.setCreator(sysUser.getId());
                reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + txt);
            } else {
                reqState1.setCreator(labMaininfo.getUnChkDoctor());
                reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + labMaininfo.getUnChkDoctorNa() + "," + txt);
            }
            labMainStateService.save(reqState1);
        }
        getIsAddFee(mainInfo);
        return Result.succ(1, "取消成功", mainInfo);
    }

    /**
     * 细菌检验记录审核逻辑
     *
     * @param mainInfo
     */
    public LabMaininfo chkBacMainInfo(LabMaininfo mainInfo) throws JsonProcessingException {
        if (StringUtils.isNotBlank(mainInfo.getPatNa())) {
            String apply = PinYinUtil.firstPinYinFun.apply(mainInfo.getPatNa());
            mainInfo.setPatPyName(apply);
        }
        /*检验结果小于0时禁止审核 jyjgxy0sjzsh*/
        SysParamParam sysp2 = new SysParamParam();
        sysp2.setParamCode("bgdyxtcs");
        sysp2.setField("jyjgxy0sjzsh");
        sysp2.setClassifyCode(mainInfo.getRptGroup());
        List<SysParamFieldValueDto> kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
        String p2Str = kcflrdstndtmLst.size() <= 0 ? "" : kcflrdstndtmLst.get(0).getValue();

        /*检验结果为空时禁止审核 jyjgwksjzsh*/
        sysp2 = new SysParamParam();
        sysp2.setParamCode("bgdyxtcs");
        sysp2.setField("jyjgwksjzsh");
        sysp2.setClassifyCode(mainInfo.getRptGroup());
        kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
        String jyjgwksjzsh = kcflrdstndtmLst.size() <= 0 ? "" : kcflrdstndtmLst.get(0).getValue();
        /*无检验医生,禁止审核*/
        if (!BeanUtil.isEmpty(jyjgwksjzsh) && jyjgwksjzsh.equals("1")) {
            int bacResultCheck = labMaininfoBacServiceImpl.getBacResultCheck(mainInfo);
            if (bacResultCheck == 0) {
                throw new RuntimeException("检验结果为空时,禁止审核");
            }
        }
        /*无检验医生禁止审核 wjyysjzsh*/
        sysp2 = new SysParamParam();
        sysp2.setParamCode("bgdyxtcs");
        sysp2.setField("wjyysjzsh");
        sysp2.setClassifyCode(mainInfo.getRptGroup());
        kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
        String wjyysjzsh = kcflrdstndtmLst.size() <= 0 ? "" : kcflrdstndtmLst.get(0).getValue();
        /*无检验医生,禁止审核*/
        if (!BeanUtil.isEmpty(wjyysjzsh) && wjyysjzsh.equals("1")) {
            if (BeanUtil.isEmpty(mainInfo.getTestDoctor())) {
                throw new RuntimeException("无检验医生,禁止审核");
            }
        }
        /*无审核医生禁止审核 wshysjzsh*/
        sysp2 = new SysParamParam();
        sysp2.setParamCode("bgdyxtcs");
        sysp2.setField("wshysjzsh");
        sysp2.setClassifyCode(mainInfo.getRptGroup());
        kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
        String wshysjzsh = kcflrdstndtmLst.size() <= 0 ? "" : kcflrdstndtmLst.get(0).getValue();
        /*无审核医生,禁止审核*/
        if (!BeanUtil.isEmpty(wshysjzsh) && wshysjzsh.equals("1")) {
            if (BeanUtil.isEmpty(mainInfo.getChkDoctor())) {
                throw new RuntimeException("无检验医生,禁止审核");
            }
        }
        /*检验、审核医生相同禁止审核 jyysshysxtjzsh*/
        sysp2 = new SysParamParam();
        sysp2.setParamCode("bgdyxtcs");
        sysp2.setField("jyysshysxtjzsh");
        sysp2.setClassifyCode(mainInfo.getRptGroup());
        kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
        String jyysshysxtjzsh = kcflrdstndtmLst.size() <= 0 ? "" : kcflrdstndtmLst.get(0).getValue();

        /*检验、审核医生相同禁止审核*/
        if (!BeanUtil.isEmpty(jyysshysxtjzsh) && jyysshysxtjzsh.equals("1")) {
            if (!BeanUtil.isEmpty(mainInfo.getChkDoctor()) && !BeanUtil.isEmpty(mainInfo.getTestDoctor()) && mainInfo.getChkDoctor().equals(mainInfo.getTestDoctor())) {
                throw new RuntimeException("检验、审核医生相同,禁止审核");
            }
        }

        /*检验结果包含以下值时禁止审核(,分隔) jyjgbhyxzsjzsh*/
        sysp2 = new SysParamParam();
        sysp2.setParamCode("bgdyxtcs");
        sysp2.setField("jyjgbhyxzsjzsh");
        sysp2.setClassifyCode(mainInfo.getRptGroup());
        kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
        String jyjgbhyxzsjzsh = kcflrdstndtmLst.size() <= 0 ? "" : kcflrdstndtmLst.get(0).getValue();

        /*无病人姓名禁止审核 wbrxmjzsh*/
        sysp2 = new SysParamParam();
        sysp2.setParamCode("bgdyxtcs");
        sysp2.setField("wbrxmjzsh");
        sysp2.setClassifyCode(mainInfo.getRptGroup());
        kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
        String wbrxmjzsh = kcflrdstndtmLst.size() <= 0 ? "" : kcflrdstndtmLst.get(0).getValue();
        /*无病人姓名禁止审核*/
        if (!BeanUtil.isEmpty(wbrxmjzsh) && wbrxmjzsh.equals("1")) {
            if (BeanUtil.isEmpty(mainInfo.getPatNa())) {
                throw new RuntimeException("无病人姓名,禁止审核");
            }
        }

        //判断流程code 有没有,没有塞
        if (StringUtils.isBlank(mainInfo.getBacFlowNode())) {
            BacTestWorkFlowNode bacTestWorkFlowNodeByLast = bacTestWorkFlowNodeService.findBacTestWorkFlowNodeByLast(mainInfo);
            mainInfo.setBacFlowNode(bacTestWorkFlowNodeByLast.getNodeNo());
        }
        /**
         * 判断细菌结果是否可以审核
         */
        int i = labMaininfoMapper.updateById(mainInfo);
        if (i <= 0) {
            return null;
        }
        /*标本流程状态记录*/
        SysUser sysUser = RedisUserManager.getUser();
        new Thread(() -> {
            /*审核后生成状态记录*/
            LabMainState reqState1 = new LabMainState();
            reqState1.setMaininfoId(mainInfo.getId());
            reqState1.setStateCode("100");//mainInfo.getIsChk().toString());
            String txt = "";
            if (mainInfo.getIsChk().equals(new BigDecimal(1))) {
                reqState1.setStateCode("99");
                txt = "初审";
            }
            if (mainInfo.getIsChk().equals(new BigDecimal(2))) {
                txt = "审核";
            }
            reqState1.setStateValue(txt + "状态");
            reqState1.setCreator(mainInfo.getChkDoctor());
            reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
            reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + txt);
            labMainStateService.save(reqState1);

            if (StringUtils.isNotBlank(mainInfo.getReqNo())) {
                /*标本状态记录*/
                LabReqMain rmEntry = StringUtils.isNotBlank(mainInfo.getReqNo()) ? labMainInfoServiceBak.getLabReqMainEntity(mainInfo.getReqNo()) : null;
                LabReqState reqState = new LabReqState();
                reqState.setReqMainId(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getId() : "");
                reqState.setSampleda(mainInfo.getSampleda());
                reqState.setSampleNo(mainInfo.getSampleNo());
                reqState.setRptGroup(mainInfo.getRptGroup());
                reqState.setReqNo(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                reqState.setStateCode(reqState1.getStateCode());
                reqState.setOrgId(mainInfo.getOrgId());
                reqState.setCreator(sysUser.getId());
                reqState.setStateValue("标本" + txt);
                String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + txt + ",标本号:" + (BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                reqState.setRemark(rmk);
                reqState.setSeq(labReqStateService.getMaxCount(mainInfo.getReqNo()));
                labReqStateService.save(reqState);

                if (BeanUtil.isNotEmpty(rmEntry)) {
                    rmEntry.setState(reqState.getStateCode());
                    rmEntry.setStateNa(reqState.getStateValue());
                    labReqMainService.saveOrUpdate(rmEntry);
                }
            }
        }).start();

        /*审核后,先删除已有报告记录，再生成报告记录*/
        Result r = previewBacRpt(mainInfo);

        //调用发送微生物报告接口
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
            /*发布报告相关*/
            for (String webUrl : collect) {
                Map releaseReportMap = new HashMap();
                String releaseReport = webUrl + "/public/releaseWswReport";
                releaseReportMap.put("orgId", sysUser.getOrgId());
                releaseReportMap.put("mainInfoId", mainInfo.getId());
                releaseReportMap.put("username", sysUser.getUsername());
                releaseReportMap.put("realname", sysUser.getRealname());
                String msg = "";
                String release = HttpUtil.createPost(releaseReport).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();
                logger.info("发布报告返回值:\n" + release);
                try {
                    JSONObject releaseObject = new JSONObject(release);
                    JSONObject releaseStatus = releaseObject.getJSONObject("status");
                    msg = releaseStatus.getStr("msg");
                    String releaseCode = releaseStatus.get("code").toString();
                    if (!"400".equals(releaseCode)) {
                        String updateUrl = webUrl + "/public/updateReportStatus";
                        Map<String, Object> updateMap = new HashMap<>();
                        //标本审核
                        updateMap.put("status", "0306");
                        updateMap.put("reqNo", mainInfo.getReqNo());
                        updateMap.put("patType", mainInfo.getPatType());
                        updateMap.put("chkDoctor", mainInfo.getChkDoctor());
                        updateMap.put("testDoctor", mainInfo.getTestDoctor());
                        updateMap.put("patType", mainInfo.getPatType());
                        updateMap.put("samplingTime", BeanUtil.isEmpty(mainInfo.getSamplingTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mainInfo.getSamplingTime()));
                        updateMap.put("signTime", BeanUtil.isEmpty(mainInfo.getSignTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mainInfo.getSignTime()));
                        updateMap.put("operateTime", BeanUtil.isEmpty(mainInfo.getTestTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mainInfo.getTestTime()));
                        updateMap.put("reportTime", BeanUtil.isEmpty(mainInfo.getChkTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mainInfo.getChkTime()));
                        updateMap.put("orgId", mainInfo.getOrgId());
                        updateMap.put("username", sysUser.getUsername());
                        updateMap.put("realname", sysUser.getRealname());
                        updateMap.put("id", mainInfo.getId());
                        String update = HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                        logger.info("更新状态返回值:\n" + update);
                    } else {
                        mainInfo.setMsg(msg);
                        //调用接口不成功，回退状态
                        LambdaQueryWrapper<LabRptmain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(LabRptmain::getRptGroup, mainInfo.getRptGroup()).eq(LabRptmain::getSampleNo, mainInfo.getSampleNo()).eq(LabRptmain::getSampleda, mainInfo.getSampleda())
                                .eq(LabRptmain::getDelFlag, 0);
                        labRptmainMapper.delete(lambdaQueryWrapper);
                        mainInfo.setIsChk(new BigDecimal(0));
                        labMaininfoService.updateById(mainInfo);
                    }
                } catch (Exception e) {
                    mainInfo.setMsg(msg);
                    //调用接口不成功，回退状态
                    LambdaQueryWrapper<LabRptmain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(LabRptmain::getRptGroup, mainInfo.getRptGroup()).eq(LabRptmain::getSampleNo, mainInfo.getSampleNo()).eq(LabRptmain::getSampleda, mainInfo.getSampleda())
                            .eq(LabRptmain::getDelFlag, 0);
                    labRptmainMapper.delete(lambdaQueryWrapper);
                    mainInfo.setIsChk(new BigDecimal(0));
                    labMaininfoService.updateById(mainInfo);
                    e.printStackTrace();
                }
            }
        }
        return mainInfo;
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public Result previewBacRpt(LabMaininfo labMaininfo) throws JsonProcessingException {
        return labMaininfoBacServiceImpl.previewBacRpt(labMaininfo);
    }

    @Override
    public Result updateIsChkBySampleNos(UpdateIsChkDto updateIsChkDto) {
        LambdaUpdateWrapper<LabMaininfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(LabMaininfo::getId, updateIsChkDto.getIds());
        if (PRELIMINARY_REVIEW.equals(updateIsChkDto.getChkStatus())) {
            updateWrapper.and(wrapper -> wrapper.eq(LabMaininfo::getIsChk, ChkStatusEnum.NOCHK.getValue()).or().isNull(LabMaininfo::getIsChk).or().eq(LabMaininfo::getIsChk, ""));
            updateWrapper.set(LabMaininfo::getIsChk, ChkStatusEnum.FIRSTCHK.getValue());
            updateWrapper.set(LabMaininfo::getChkDoctor, updateIsChkDto.getChkDoctor());
            updateWrapper.set(LabMaininfo::getChkTime, new Timestamp(System.currentTimeMillis()));
        } else if (CANCEL_PRELIMINARY_REVIEW.equals(updateIsChkDto.getChkStatus())) {
            updateWrapper.eq(LabMaininfo::getIsChk, ChkStatusEnum.FIRSTCHK.getValue());
            updateWrapper.set(LabMaininfo::getIsChk, ChkStatusEnum.NOCHK.getValue());
            updateWrapper.set(LabMaininfo::getChkDoctor, updateIsChkDto.getChkDoctor());
            updateWrapper.set(LabMaininfo::getChkTime, new Timestamp(System.currentTimeMillis()));
        } else if (REVIEW.equals(updateIsChkDto.getChkStatus())) {
            updateWrapper.eq(LabMaininfo::getIsChk, ChkStatusEnum.FIRSTCHK.getValue());
            updateWrapper.set(LabMaininfo::getIsChk, ChkStatusEnum.ISCHK.getValue());
            updateWrapper.set(LabMaininfo::getChkDoctor, updateIsChkDto.getChkDoctor());
            updateWrapper.set(LabMaininfo::getChkTime, new Timestamp(System.currentTimeMillis()));
        } else {
            updateWrapper.eq(LabMaininfo::getIsChk, ChkStatusEnum.ISCHK.getValue());
            updateWrapper.set(LabMaininfo::getIsChk, ChkStatusEnum.FIRSTCHK.getValue());
            updateWrapper.set(LabMaininfo::getChkDoctor, updateIsChkDto.getChkDoctor());
            updateWrapper.set(LabMaininfo::getChkTime, new Timestamp(System.currentTimeMillis()));
        }

        this.update(null, updateWrapper);


        return Result.succ(1, "", null);
    }

    private void specialLabRptHandle
            (List<PubReportRules> reportRules, List<LabRptresult> rptresultList, List<ReportPreviewDto> reportPreviewDtos, LabMaininfo
                    labMaininfo) {
        //提取特殊报告模板，并从reportRules中移除特殊报告
        List<PubReportRules> reportRulesRuleType5s = new ArrayList<>();//特殊报告
        for (PubReportRules pubReportRules : reportRules) {
            if ("5".equals(pubReportRules.getRuleType())) {
                reportRulesRuleType5s.add(pubReportRules);
            }
        }
        //循环reportRulesRuleType5s,判断是否符合要求后加入reportPreviewDtos
        for (PubReportRules pubReportRules : reportRulesRuleType5s) {
            //从reportRules中删除特殊报告模板，避免重复判断
            reportRules.remove(pubReportRules);
            if ("0".equals(pubReportRules.getIsUse())) {
                continue;
            }
            //rptresultList循环，逐报告项目判断是否满足条件
            for (LabRptresult rptresult : rptresultList) {
                String sql = "select count(1) as result from dual where 1=1 ";
                String afterReplace = new CalcItemFormulaReplcae().ReplaceCondition(pubReportRules.getRules().toLowerCase(), labMaininfo, rptresult);
                if (!StringUtils.isEmpty(afterReplace)) {
                    sql += " and " + afterReplace;
                }
                logger.info("sql:" + sql);
                try {
                    List<Map<String, Object>> calcResult = labRptresultMapper.getTableDataBySql(sql);
                    // 遍历 List 中的每个 Map
                    String ResValue = "";
                    for (Map<String, Object> map : calcResult) {
                        // 遍历 Map 中的键值对
                        for (Map.Entry<String, Object> entry : map.entrySet()) {
                            String key = entry.getKey();
                            Object value = entry.getValue();
                            ResValue = value.toString();
                        }
                    }
                    //只要有一个检验项目满足则记录到reportPreviewDtos,不再继续其他检验项目判断
                    //此处逻辑有可能不健全，待优化
                    if (!StringUtils.isEmpty(ResValue) && ResValue.equals("1")) {
                        ReportPreviewDto reportPreviewDto = new ReportPreviewDto();
                        reportPreviewDto.setId(labMaininfo.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setReportId(pubReportRules.getReportId());
                        reportPreviewDto.setReportTemplateName(pubReportRules.getReportName());
                        //判断reportPreviewDtos是否包含reportPreviewDto，则不加入
//                        if (reportPreviewDtos.contains(reportPreviewDto)){
//                            break;
//                        }
                        reportPreviewDtos.add(reportPreviewDto);
                        return;
                        //break;
                    }
                } catch (Exception e) {

                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result previewRpt(LabMaininfo labMaininfo, int printFlag) {
        if (ToolsUtils.isEmpty(labMaininfo)) {
            return Result.fail("入参异常！");
        }
        logger.info("开始生成报告，主业务表id为" + labMaininfo.getId());
        //根据报告单元获取模版codeR
        MPJLambdaWrapper<PubReportRules> reportRulesWrapper = new MPJLambdaWrapper<>();
        reportRulesWrapper.selectAll(PubReportRules.class);
        reportRulesWrapper.selectAs(PubReport::getName, PubReportRules::getReportName);
        reportRulesWrapper.leftJoin(PubReport.class, PubReport::getCode, PubReportRules::getReportCode);
        reportRulesWrapper.eq(PubReportRules::getDelFlag, 0);
        reportRulesWrapper.eq(PubReportRules::getRptGroup, labMaininfo.getRptGroup());
        reportRulesWrapper.orderByAsc(PubReportRules::getRuleType);
        reportRulesWrapper.orderByAsc(PubReportRules::getPriorityLevel);
        List<PubReportRules> reportRules = reportRulesMapper.selectList(reportRulesWrapper);
        if (ToolsUtils.isEmpty(reportRules) || reportRules.size() == 0) {
            return Result.fail("根据报告单元未获取到报告模版！");
        }

        List<String> pubReportIds = reportRules.stream().map(p -> p.getReportCode()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(pubReportIds)) {
            return Result.fail("根据报告单元规则未获取到报告模版！");
        }

        int i = 0;
        String mainInfoId = labMaininfo.getId();//检验记录主键
        MPJLambdaWrapper<LabRptmain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabRptmain.class);
        queryWrapper.selectAs("pubrpt", PubReport::getPaperSize, LabRptmain::getPageUnit);
        queryWrapper.eq(LabRptmain::getDelFlag, 0);
        queryWrapper.eq(LabRptmain::getMainInfoId, mainInfoId);
        queryWrapper.leftJoin(PubReport.class, "pubrpt", p -> p.eq(PubReport::getId, LabRptmain::getRptTemplateCode));

        /*SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isNotEmpty(sysUser)) {
            queryWrapper.eq(LabRptmain::getOrgId, sysUser.getOrgId());
        }*/
        List<LabRptmain> labRptmainList = labRptmainMapper.selectList(queryWrapper);
        LabMaininfo labMaininfo1 = labMaininfoMapper.selectById(mainInfoId);
        ReportPreviewDto reportPreviewDto;
        List<ReportPreviewDto> reportPreviewDtos = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(labMaininfo1.getIsChk()) && "2".equals(labMaininfo1.getIsChk().toString()) && CollectionUtils.isNotEmpty(labRptmainList) && printFlag == 2) {
            for (LabRptmain labRptmain : labRptmainList) {
                reportPreviewDto = new ReportPreviewDto();
                reportPreviewDto.setId(labRptmain.getId());
                reportPreviewDto.setIsChecked(true);
                reportPreviewDto.setReportId(labRptmain.getRptTemplateCode());
                reportPreviewDto.setReportTemplateName(pubReportMapper.selectById(labRptmain.getRptTemplateCode()).getName());
                reportPreviewDto.setPageUnit(labRptmain.getPageUnit());

                reportPreviewDtos.add(reportPreviewDto);
            }
            return Result.succ(1, "成功", reportPreviewDtos);
        }
        if (ToolsUtils.isNotEmpty(labRptmainList)) {
            for (LabRptmain labRptmain : labRptmainList) {
                LambdaQueryWrapper<LabRptdetail> delLabRptdetailWrapper = new LambdaQueryWrapper<>();
                delLabRptdetailWrapper.eq(LabRptdetail::getRptMainCode, labRptmain.getRptCode());
                labRptdetailMapper.delete(delLabRptdetailWrapper);
                labRptmainMapper.deleteById(labRptmain.getId());
            }
        }

        LambdaQueryWrapper<PubReport> queryPubReportWrapper = new LambdaQueryWrapper<>();
        queryPubReportWrapper.eq(PubReport::getDelFlag, 0);
        queryPubReportWrapper.in(PubReport::getId, pubReportIds);
        List<PubReport> pubReports = pubReportMapper.selectList(queryPubReportWrapper);

        //根基检验信息查询结果信息
        LambdaQueryWrapper<LabRptresult> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabRptresult::getDelFlag, 0);
        //.eq(LabRptresult::getMaininfoId, labMaininfo.getId());
        Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        wrapper.ge(LabRptresult::getSampleda, startTime);
        wrapper.le(LabRptresult::getSampleda, endTime);
        wrapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
        wrapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
        List<LabRptresult> rptresultList = labRptresultMapper.selectList(wrapper);

        List<LabRptresult> equalList;
        List<LabRptresult> notEqualList;
        LabRptmain labRptmain;
        //特殊报告判断写入reportPreviewDtos

        labMaininfoServiceExtend.specialLabRptHandle(reportRules, rptresultList, reportPreviewDtos, labMaininfo);
        //若预览中数据则展示特殊报告
        if (reportPreviewDtos.size() > 0) {
            labRptmain = new LabRptmain();
            labRptmain.setOrgId(labRptmain.getOrgId());
            labRptmain.setMainInfoId(labMaininfo.getId());
            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
            labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
            labRptmain.setSampleda(labMaininfo.getSampleda());
            labRptmain.setSampleNo(labMaininfo.getSampleNo());
            labRptmain.setRptTemplateCode(reportPreviewDtos.get(0).getReportId());
            labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
            labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
            labRptmain.setIsExported(0);

            List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(rptEntries)) {
                labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
            }

            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
            i = labRptmainMapper.insert(labRptmain);
            reportPreviewDtos.get(0).setId(labRptmain.getId());
            return Result.succ(1, "成功", reportPreviewDtos);
        }
        PubReportRules pubReportRulesEntry = reportRules.get(reportRules.size() - 1);
        if (ToolsUtils.isEmpty(pubReportRulesEntry)) {
            return Result.fail("查不到报告模板规则");
        }
        String ruleType = pubReportRulesEntry.getRuleType();
        logger.info("开始生成报告，规则类型为" + ruleType);
        if (Objects.equals(ruleType, "4")) {
            LambdaQueryWrapper<LabRulesVsItemdict> queryWrapperVS = new LambdaQueryWrapper<>();
            queryWrapperVS.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(reportRules.size() - 1).getId()).eq(LabRulesVsItemdict::getType, "1");
            List<LabRulesVsItemdict> rulesVsItemdicts = rulesVsItemdictMapper.selectList(queryWrapperVS);
            if (rulesVsItemdicts.size() > 0) {
                boolean isAnyContained = rptresultList.stream().anyMatch(rule -> rulesVsItemdicts.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));
                //满足拆分条件，则存储报告信息
                if (isAnyContained && "1".equals(pubReportRulesEntry.getIsSplit())) {
                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                    labRptmain = new LabRptmain();
                    labRptmain.setOrgId(labRptmain.getOrgId());
                    labRptmain.setMainInfoId(labMaininfo.getId());
                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                    labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                    labRptmain.setSampleda(labMaininfo.getSampleda());
                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                    labRptmain.setRptTemplateCode(reportRules.get(reportRules.size() - 1).getReportId());
                    labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                    labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                    labRptmain.setIsExported(0);

                    List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(rptEntries)) {
                        labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                    }

                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                    i = labRptmainMapper.insert(labRptmain);
                    //插入LAB_RPTDETAIL表
                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                        //找到与rulesVsItemdicts中的itemDictCode相等的记录
                        equalList = rptresultList.stream().filter(rule -> rulesVsItemdicts.stream().anyMatch(result -> result.getItemDictCode().equals(rule.getItemNo()))).collect(Collectors.toList()); //将结果转化为List
                        if (ToolsUtils.isNotEmpty(equalList)) {
                            for (LabRptresult labRptresult : equalList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(labRptmain.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                    }
                    //返回报告预览需要的数据 [{id:'1',isChecked:true,reportObjectCode:'XXXXX生化报告'},{id:'2',isChecked:false,reportObjectCode:'XXXXX免疫报告'}]

                    reportPreviewDto = new ReportPreviewDto();
                    reportPreviewDto.setId(labRptmain.getId());
                    reportPreviewDto.setIsChecked(false);
                    reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                    reportPreviewDto.setReportId(reportRules.get(reportRules.size() - 1).getReportId());
                    reportPreviewDto.setReportTemplateName(reportRules.get(reportRules.size() - 1).getReportName());
                    reportPreviewDtos.add(reportPreviewDto);
                }

                //不拆分，且满足规则四，按规则四生成报告，其他规则不再使用
                if (isAnyContained && !"1".equals(pubReportRulesEntry.getIsSplit())) {
                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                    labRptmain = new LabRptmain();
                    labRptmain.setOrgId(labRptmain.getOrgId());
                    labRptmain.setMainInfoId(labMaininfo.getId());
                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                    labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                    labRptmain.setSampleda(labMaininfo.getSampleda());
                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                    labRptmain.setRptTemplateCode(reportRules.get(reportRules.size() - 1).getReportId());
                    labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                    labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                    labRptmain.setIsExported(0);

                    List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(rptEntries)) {
                        labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                    }

                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                    i = labRptmainMapper.insert(labRptmain);
                    //插入LAB_RPTDETAIL表
                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                        //找到与rulesVsItemdicts中的itemDictCode相等的记录
                        equalList = rptresultList.stream().filter(rule -> rulesVsItemdicts.stream().anyMatch(result -> result.getItemDictCode().equals(rule.getItemNo()))).collect(Collectors.toList()); //将结果转化为List
                        if (ToolsUtils.isNotEmpty(equalList)) {
                            for (LabRptresult labRptresult : equalList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(labRptmain.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                    }
                    //返回报告预览需要的数据 [{id:'1',isChecked:true,reportObjectCode:'XXXXX生化报告'},{id:'2',isChecked:false,reportObjectCode:'XXXXX免疫报告'}]

                    reportPreviewDto = new ReportPreviewDto();
                    reportPreviewDto.setId(labRptmain.getId());
                    reportPreviewDto.setIsChecked(false);
                    reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                    reportPreviewDto.setReportId(reportRules.get(reportRules.size() - 1).getReportId());
                    reportPreviewDto.setReportTemplateName(reportRules.get(reportRules.size() - 1).getReportName());
                    reportPreviewDtos.add(reportPreviewDto);
                    return Result.succ(1, "预览成功", reportPreviewDtos);
                }

                //找到与rulesVsItemdicts中的itemDictCode不相等的记录
                notEqualList = rptresultList.stream().filter(rule -> rulesVsItemdicts.stream().noneMatch(result -> result.getItemDictCode().equals(rule.getItemNo()))).collect(Collectors.toList()); //将结果转化为List

                /*检验结果中不再除了规则四中的数据  不再有其他项目部署，则不再进行生成报告*/
                if (ToolsUtils.isEmpty(notEqualList) || notEqualList.size() <= 0) {
                    return Result.succ(1, "预览成功", reportPreviewDtos);
                }

                int size = reportRules.size() - 2;
                if (size < 0) {
                    return Result.fail("没有找到报表,请维护报表后重试");
                }
                String ruleType1 = reportRules.get(size).getRuleType();
                switch (ruleType1) {
                    case "3":
                        if (notEqualList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                            //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                            logger.info("3333333333333333333333333333333333333333333");
                            labRptmain = new LabRptmain();
                            labRptmain.setOrgId(labMaininfo.getOrgId());
                            labRptmain.setMainInfoId(labMaininfo.getId());
                            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                            labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                            labRptmain.setSampleda(labMaininfo.getSampleda());
                            labRptmain.setSampleNo(labMaininfo.getSampleNo());
                            labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                            labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                            labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                            labRptmain.setIsExported(0);
                            List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(rptEntries)) {
                                labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                            }
                            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                            i = labRptmainMapper.insert(labRptmain);
                            //插入LAB_RPTDETAIL表
                            if (ToolsUtils.isNotEmpty(rptresultList)) {
                                if (ToolsUtils.isNotEmpty(notEqualList)) {
                                    for (LabRptresult labRptresult : notEqualList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(labMaininfo.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                            }
                            reportPreviewDto = new ReportPreviewDto();
                            reportPreviewDto.setId(labRptmain.getId());
                            reportPreviewDto.setIsChecked(true);
                            reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                            reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                            reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                            reportPreviewDtos.add(reportPreviewDto);
                        } else {

                            size = reportRules.size() - 3;
                            if (size < 0) {
                                return Result.fail("没有找到报表,请维护报表后重试");
                            }
                            String ruleType2 = reportRules.get(size).getRuleType();
                            if (Objects.equals(ruleType2, "2")) {
                                LambdaQueryWrapper<LabRulesVsItemdict> queryWrapper1 = new LambdaQueryWrapper<>();
                                queryWrapper1.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(size).getId()).eq(LabRulesVsItemdict::getType, "0");
                                List<LabRulesVsItemdict> rulesVsItemdict = rulesVsItemdictMapper.selectList(queryWrapper1);

                                boolean anyMatch = rptresultList.stream().anyMatch(rule -> rulesVsItemdict.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));

                                if (anyMatch || notEqualList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                                    labRptmain = new LabRptmain();
                                    labRptmain.setOrgId(labMaininfo.getOrgId());
                                    labRptmain.setMainInfoId(labMaininfo.getId());
                                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                                    labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                                    labRptmain.setSampleda(labMaininfo.getSampleda());
                                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                                    labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                                    labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                                    labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                                    labRptmain.setIsExported(0);
                                    List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                                    if (CollectionUtils.isNotEmpty(rptEntries)) {
                                        labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                                    }
                                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                                    i = labRptmainMapper.insert(labRptmain);
                                    //插入LAB_RPTDETAIL表
                                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                                        if (ToolsUtils.isNotEmpty(notEqualList)) {
                                            for (LabRptresult labRptresult : notEqualList) {
                                                LabRptdetail rptdetail = new LabRptdetail();
                                                rptdetail.setOrgId(labMaininfo.getOrgId());
                                                rptdetail.setRptMainCode(labRptmain.getId());
                                                rptdetail.setRptResultId(labRptresult.getId());
                                                i = labRptdetailMapper.insert(rptdetail);
                                            }
                                        }
                                    }
                                    reportPreviewDto = new ReportPreviewDto();
                                    reportPreviewDto.setId(labRptmain.getId());
                                    reportPreviewDto.setIsChecked(true);
                                    reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                                    reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                                    reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                                    reportPreviewDtos.add(reportPreviewDto);
                                } else {
                                    size = reportRules.size() - 4;
                                    if (size < 0) {
                                        return Result.fail("没有找到报表,请维护报表后重试");
                                    }

                                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                                    labRptmain = new LabRptmain();
                                    labRptmain.setOrgId(labMaininfo.getOrgId());
                                    labRptmain.setMainInfoId(labMaininfo.getId());
                                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                                    labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                                    labRptmain.setSampleda(labMaininfo.getSampleda());
                                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                                    labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                                    labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                                    labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                                    labRptmain.setIsExported(0);
                                    List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                                    if (CollectionUtils.isNotEmpty(rptEntries)) {
                                        labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                                    }
                                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                                    i = labRptmainMapper.insert(labRptmain);
                                    //插入LAB_RPTDETAIL表
                                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                                        if (ToolsUtils.isNotEmpty(notEqualList)) {
                                            for (LabRptresult labRptresult : notEqualList) {
                                                LabRptdetail rptdetail = new LabRptdetail();
                                                rptdetail.setOrgId(labMaininfo.getOrgId());
                                                rptdetail.setRptMainCode(labRptmain.getId());
                                                rptdetail.setRptResultId(labRptresult.getId());
                                                i = labRptdetailMapper.insert(rptdetail);
                                            }
                                        }
                                    }
                                    reportPreviewDto = new ReportPreviewDto();
                                    reportPreviewDto.setId(labRptmain.getId());
                                    reportPreviewDto.setIsChecked(true);
                                    reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                                    reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                                    reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                                    reportPreviewDtos.add(reportPreviewDto);
                                }
                            }
                        }
                        break;
                    case "2":
                        logger.info("22222222222222222222222222222222222");
                        LambdaQueryWrapper<LabRulesVsItemdict> queryWrapper1 = new LambdaQueryWrapper<>();
                        queryWrapper1.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(size).getId()).eq(LabRulesVsItemdict::getType, "0");
                        List<LabRulesVsItemdict> rulesVsItemdict = rulesVsItemdictMapper.selectList(queryWrapper1);

                        boolean anyMatch = rptresultList.stream().anyMatch(rule -> rulesVsItemdict.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));

                        if (anyMatch || notEqualList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                            //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                            labRptmain = new LabRptmain();
                            labRptmain.setOrgId(labMaininfo.getOrgId());
                            labRptmain.setMainInfoId(labMaininfo.getId());
                            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                            labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                            labRptmain.setSampleda(labMaininfo.getSampleda());
                            labRptmain.setSampleNo(labMaininfo.getSampleNo());
                            labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                            labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                            labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                            labRptmain.setIsExported(0);
                            List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(rptEntries)) {
                                labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                            }
                            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                            i = labRptmainMapper.insert(labRptmain);
                            //插入LAB_RPTDETAIL表
                            if (ToolsUtils.isNotEmpty(rptresultList)) {
                                if (ToolsUtils.isNotEmpty(notEqualList)) {
                                    for (LabRptresult labRptresult : notEqualList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(labMaininfo.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                            }
                            reportPreviewDto = new ReportPreviewDto();
                            reportPreviewDto.setId(labRptmain.getId());
                            reportPreviewDto.setIsChecked(true);
                            reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                            reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                            reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                            reportPreviewDtos.add(reportPreviewDto);
                        } else {
                            size = reportRules.size() - 3;
                            if (size < 0) {
                                return Result.fail("没有找到报表,请维护报表后重试");
                            }

                            //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                            labRptmain = new LabRptmain();
                            labRptmain.setOrgId(labMaininfo.getOrgId());
                            labRptmain.setMainInfoId(labMaininfo.getId());
                            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                            labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                            labRptmain.setSampleda(labMaininfo.getSampleda());
                            labRptmain.setSampleNo(labMaininfo.getSampleNo());
                            labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                            labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                            labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                            labRptmain.setIsExported(0);
                            List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(rptEntries)) {
                                labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                            }
                            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                            i = labRptmainMapper.insert(labRptmain);
                            //插入LAB_RPTDETAIL表
                            if (ToolsUtils.isNotEmpty(rptresultList)) {
                                if (ToolsUtils.isNotEmpty(notEqualList)) {
                                    for (LabRptresult labRptresult : notEqualList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(labMaininfo.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                            }
                            reportPreviewDto = new ReportPreviewDto();
                            reportPreviewDto.setId(labRptmain.getId());
                            reportPreviewDto.setIsChecked(true);
                            reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                            reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                            reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                            reportPreviewDtos.add(reportPreviewDto);
                        }
                        break;
                    default:
                        //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                        logger.info("11111111111111111111111111111");
                        labRptmain = new LabRptmain();
                        labRptmain.setOrgId(labMaininfo.getOrgId());
                        labRptmain.setMainInfoId(labMaininfo.getId());
                        labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                        labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                        labRptmain.setSampleda(labMaininfo.getSampleda());
                        labRptmain.setSampleNo(labMaininfo.getSampleNo());
                        labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                        labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                        labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                        labRptmain.setIsExported(0);
                        List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(rptEntries)) {
                            labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                        }
                        labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                        i = labRptmainMapper.insert(labRptmain);
                        //插入LAB_RPTDETAIL表
                        if (ToolsUtils.isNotEmpty(rptresultList)) {
                            if (ToolsUtils.isNotEmpty(notEqualList)) {
                                for (LabRptresult labRptresult : notEqualList) {
                                    LabRptdetail rptdetail = new LabRptdetail();
                                    rptdetail.setOrgId(labMaininfo.getOrgId());
                                    rptdetail.setRptMainCode(labRptmain.getId());
                                    rptdetail.setRptResultId(labRptresult.getId());
                                    i = labRptdetailMapper.insert(rptdetail);
                                }
                            }
                        }
                        reportPreviewDto = new ReportPreviewDto();
                        reportPreviewDto.setId(labRptmain.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                        reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                        reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                        reportPreviewDtos.add(reportPreviewDto);
                        break;
                }
                return Result.succ(1, "预览成功", reportPreviewDtos);
            }

        } else {
            int size = reportRules.size() - 1;
            if (size < 0) {
                return Result.fail("查找报表失败,请维护后重试");
            }
            String ruleType1 = reportRules.get(size).getRuleType();
            switch (ruleType1) {
                case "3":
                    if (rptresultList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                        logger.info("333333333333333333333333333333333333");
                        //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                        labRptmain = new LabRptmain();
                        labRptmain.setOrgId(labMaininfo.getOrgId());
                        labRptmain.setMainInfoId(labMaininfo.getId());
                        labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                        labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                        labRptmain.setSampleda(labMaininfo.getSampleda());
                        labRptmain.setSampleNo(labMaininfo.getSampleNo());
                        labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                        labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                        labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                        labRptmain.setIsExported(0);
                        List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(rptEntries)) {
                            labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                        }
                        labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                        i = labRptmainMapper.insert(labRptmain);
                        //插入LAB_RPTDETAIL表
                        if (ToolsUtils.isNotEmpty(rptresultList)) {
                            for (LabRptresult labRptresult : rptresultList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(labMaininfo.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                        reportPreviewDto = new ReportPreviewDto();
                        reportPreviewDto.setId(labRptmain.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                        reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                        reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                        reportPreviewDtos.add(reportPreviewDto);
                    } else {
                        size = reportRules.size() - 2;
                        if (size < 0) {
                            return Result.fail("查找报表失败,请维护后重试");
                        }
                        ruleType1 = reportRules.get(size).getRuleType();
                        if (Objects.equals(ruleType1, "2")) {
                            LambdaQueryWrapper<LabRulesVsItemdict> queryWrapper1 = new LambdaQueryWrapper<>();
                            queryWrapper1.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(size).getId()).eq(LabRulesVsItemdict::getType, "0");
                            List<LabRulesVsItemdict> rulesVsItemdict = rulesVsItemdictMapper.selectList(queryWrapper1);

                            boolean anyMatch = rptresultList.stream().anyMatch(rule -> rulesVsItemdict.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));


                            if (anyMatch || rptresultList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                                //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                                labRptmain = new LabRptmain();
                                labRptmain.setOrgId(labMaininfo.getOrgId());
                                labRptmain.setMainInfoId(labMaininfo.getId());
                                labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                                labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                                labRptmain.setSampleda(labMaininfo.getSampleda());
                                labRptmain.setSampleNo(labMaininfo.getSampleNo());
                                labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                                labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                                labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                                labRptmain.setIsExported(0);
                                List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                                if (CollectionUtils.isNotEmpty(rptEntries)) {
                                    labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                                }
                                labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                                i = labRptmainMapper.insert(labRptmain);
                                //插入LAB_RPTDETAIL表
                                if (ToolsUtils.isNotEmpty(rptresultList)) {
                                    for (LabRptresult labRptresult : rptresultList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(labMaininfo.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                                reportPreviewDto = new ReportPreviewDto();
                                reportPreviewDto.setId(labRptmain.getId());
                                reportPreviewDto.setIsChecked(true);
                                reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                                reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                                reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                                reportPreviewDtos.add(reportPreviewDto);
                            } else {
                                size = reportRules.size() - 3;
                                if (size < 0) {
                                    return Result.fail("查找报表失败,请维护后重试");
                                }
                                //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                                labRptmain = new LabRptmain();
                                labRptmain.setOrgId(labMaininfo.getOrgId());
                                labRptmain.setMainInfoId(labMaininfo.getId());
                                labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                                labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                                labRptmain.setSampleda(labMaininfo.getSampleda());
                                labRptmain.setSampleNo(labMaininfo.getSampleNo());
                                labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                                labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                                labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                                labRptmain.setIsExported(0);
                                List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                                if (CollectionUtils.isNotEmpty(rptEntries)) {
                                    labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                                }
                                labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                                i = labRptmainMapper.insert(labRptmain);
                                //插入LAB_RPTDETAIL表
                                if (ToolsUtils.isNotEmpty(rptresultList)) {
                                    for (LabRptresult labRptresult : rptresultList) {
                                        LabRptdetail rptdetail = new LabRptdetail();
                                        rptdetail.setOrgId(labMaininfo.getOrgId());
                                        rptdetail.setRptMainCode(labRptmain.getId());
                                        rptdetail.setRptResultId(labRptresult.getId());
                                        i = labRptdetailMapper.insert(rptdetail);
                                    }
                                }
                                reportPreviewDto = new ReportPreviewDto();
                                reportPreviewDto.setId(labRptmain.getId());
                                reportPreviewDto.setIsChecked(true);
                                reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                                reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                                reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                                reportPreviewDtos.add(reportPreviewDto);
                            }
                        }
                    }
                    break;
                case "2":
                    logger.info("22222222222222222222222222222222222");
                    LambdaQueryWrapper<LabRulesVsItemdict> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(LabRulesVsItemdict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, reportRules.get(size).getId()).eq(LabRulesVsItemdict::getType, "0");
                    List<LabRulesVsItemdict> rulesVsItemdict = rulesVsItemdictMapper.selectList(queryWrapper1);

                    boolean anyMatch = rptresultList.stream().anyMatch(rule -> rulesVsItemdict.stream().anyMatch(rpt -> rule.getItemNo().equals(rpt.getItemDictCode())));


                    if (anyMatch || rptresultList.size() >= Integer.parseInt(reportRules.get(size).getRules())) {
                        //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                        labRptmain = new LabRptmain();
                        labRptmain.setOrgId(labMaininfo.getOrgId());
                        labRptmain.setMainInfoId(labMaininfo.getId());
                        labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                        labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                        labRptmain.setSampleda(labMaininfo.getSampleda());
                        labRptmain.setSampleNo(labMaininfo.getSampleNo());
                        labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                        labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                        labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                        labRptmain.setIsExported(0);
                        List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(rptEntries)) {
                            labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                        }
                        labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                        i = labRptmainMapper.insert(labRptmain);
                        //插入LAB_RPTDETAIL表
                        if (ToolsUtils.isNotEmpty(rptresultList)) {
                            for (LabRptresult labRptresult : rptresultList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(labMaininfo.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                        reportPreviewDto = new ReportPreviewDto();
                        reportPreviewDto.setId(labRptmain.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                        reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                        reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                        reportPreviewDtos.add(reportPreviewDto);
                    } else {
                        size = reportRules.size() - 2;
                        if (size < 0) {
                            return Result.fail("查找报表失败,请维护后重试");
                        }
                        //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                        labRptmain = new LabRptmain();
                        labRptmain.setOrgId(labMaininfo.getOrgId());
                        labRptmain.setMainInfoId(labMaininfo.getId());
                        labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                        labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                        labRptmain.setSampleda(labMaininfo.getSampleda());
                        labRptmain.setSampleNo(labMaininfo.getSampleNo());
                        labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                        labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                        labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                        labRptmain.setIsExported(0);
                        List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(rptEntries)) {
                            labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                        }
                        labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                        i = labRptmainMapper.insert(labRptmain);
                        //插入LAB_RPTDETAIL表
                        if (ToolsUtils.isNotEmpty(rptresultList)) {
                            for (LabRptresult labRptresult : rptresultList) {
                                LabRptdetail rptdetail = new LabRptdetail();
                                rptdetail.setOrgId(labMaininfo.getOrgId());
                                rptdetail.setRptMainCode(labRptmain.getId());
                                rptdetail.setRptResultId(labRptresult.getId());
                                i = labRptdetailMapper.insert(rptdetail);
                            }
                        }
                        reportPreviewDto = new ReportPreviewDto();
                        reportPreviewDto.setId(labRptmain.getId());
                        reportPreviewDto.setIsChecked(true);
                        reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                        reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                        reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                        reportPreviewDtos.add(reportPreviewDto);
                    }
                    break;
                default:
                    logger.info("1111111111111111111111111111111111111111");
                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                    labRptmain = new LabRptmain();
                    labRptmain.setOrgId(labMaininfo.getOrgId());
                    labRptmain.setMainInfoId(labMaininfo.getId());
                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                    labRptmain.setRptGroup(labMaininfo.getRptGroup());//报告单元id
                    labRptmain.setSampleda(labMaininfo.getSampleda());
                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                    labRptmain.setRptTemplateCode(reportRules.get(size).getReportId());
                    labRptmain.setPublishDoctor(labMaininfo.getChkDoctor());
                    labRptmain.setPublishDoctorNa(labMaininfo.getChkDoctorNa());
                    labRptmain.setIsExported(0);
                    List<PubReport> rptEntries = pubReports.stream().filter(p -> p.getId().equals(reportRules.get(reportRules.size() - 1).getReportId())).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(rptEntries)) {
                        labRptmain.setPageUnit(rptEntries.get(0).getPaperSize());
                    }
                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                    i = labRptmainMapper.insert(labRptmain);
                    //插入LAB_RPTDETAIL表
                    if (ToolsUtils.isNotEmpty(rptresultList)) {
                        for (LabRptresult labRptresult : rptresultList) {
                            LabRptdetail rptdetail = new LabRptdetail();
                            rptdetail.setOrgId(labMaininfo.getOrgId());
                            rptdetail.setRptMainCode(labRptmain.getId());
                            rptdetail.setRptResultId(labRptresult.getId());
                            i = labRptdetailMapper.insert(rptdetail);
                        }
                    }
                    reportPreviewDto = new ReportPreviewDto();
                    reportPreviewDto.setId(labRptmain.getId());
                    reportPreviewDto.setIsChecked(true);
                    reportPreviewDto.setPageUnit(labRptmain.getPageUnit());
                    reportPreviewDto.setReportId(reportRules.get(size).getReportId());
                    reportPreviewDto.setReportTemplateName(reportRules.get(size).getReportName());
                    reportPreviewDtos.add(reportPreviewDto);
                    break;
            }
        }
        logger.info("生成报告成功！！！！！！！！！！！！！！！！！！！！！！");
        //  reportPreviewDto.set
        if (i > 0) {
            return Result.succ(1, "成功", reportPreviewDtos);
        } else {
            return Result.fail("预览数据失败！");
        }
    }


    @Override
    public Result findLabMainInfoList(LabMainInfoDto mainInfoDto) {
        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.selectAs(LabRptGroup::getBusinessType, LabMaininfo::getBusinessType);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        queryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        queryWrapper.selectAs("test", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        queryWrapper.selectAs("chk", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        queryWrapper.selectAs("rechk", SysUser::getRealname, LabMaininfo::getReChkDoctorNa);
        queryWrapper.selectAs("prt", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("sampl", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        queryWrapper.selectAs("signer", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.leftJoin(LabRptGroup.class, LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        queryWrapper.leftJoin(LabSampleType.class, LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType);
        queryWrapper.leftJoin(SysOrgDepartment.class, SysOrgDepartment::getCode, LabMaininfo::getReqDept);
        queryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "test", SysUser::getUsername, LabMaininfo::getTestDoctor);
        queryWrapper.leftJoin(SysUser.class, "chk", SysUser::getUsername, LabMaininfo::getChkDoctor);
        queryWrapper.leftJoin(SysUser.class, "rechk", SysUser::getUsername, LabMaininfo::getReChkDoctor);
        queryWrapper.leftJoin(SysUser.class, "prt", SysUser::getUsername, LabMaininfo::getPrintDoctor);
        queryWrapper.leftJoin(SysUser.class, "sampl", SysUser::getUsername, LabMaininfo::getSamplingDoctor);
        queryWrapper.leftJoin(SysUser.class, "signer", SysUser::getUsername, LabMaininfo::getSignerDoctor);
        queryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);

        int days = mainInfoDto.getDays();
        if (days > 0) {
            int abs = Math.abs(days);
            DateTime dateTime = DateUtil.offsetDay(new Date(), abs);
            queryWrapper.ge(LabMaininfo::getReqTime, dateTime).le(LabMaininfo::getReqTime, dateTime);
        }

        if (!StringUtils.isEmpty(mainInfoDto.getPattype())) {
            queryWrapper.eq(LabMaininfo::getPatType, mainInfoDto.getPattype());
        }
        queryWrapper.eq(LabMaininfo::getPatNo, mainInfoDto.getPatNo());
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);
        //获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();

        for (LabMaininfo maininfo : labMaininfos) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(1, "查询成功", labMaininfos);
    }

    /**
     * 检验记录审核逻辑
     *
     * @param mainInfo
     */
    @Transactional
    public LabMaininfo chkLabMainInfo(LabMaininfo mainInfo, BigDecimal chkState, String caType) {
        try {
            /*检验结果小于0时禁止审核 jyjgxy0sjzsh*/
            String p2Str = "";
            SysParamParam sysp2 = new SysParamParam();
            List<SysParamFieldValueDto> kcflrdstndtmLst = null;
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "jyjgxy0sjzsh", mainInfo.getRptGroup(), null);
                p2Str = paramResult.getValueStr();
            } catch (Exception e) {
                //TODO
            }

            /*检验结果为空时禁止审核 jyjgwksjzsh*/
            String jyjgwksjzsh = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "jyjgwksjzsh", mainInfo.getRptGroup(), null);
                jyjgwksjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                //TODO
            }

            /*无检验医生禁止审核 wjyysjzsh*/
            String wjyysjzsh = "";
            try {
                /*sysp2 = new SysParamParam();
                sysp2.setParamCode("bgdyxtcs");
                sysp2.setField("wjyysjzsh");
                sysp2.setClassifyCode(mainInfo.getRptGroup());
                kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                wjyysjzsh = kcflrdstndtmLst.get(0).getValue();*/
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "wjyysjzsh", mainInfo.getRptGroup(), null);
                wjyysjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                //TODO
            }
            /*无审核医生禁止审核 wshysjzsh*/
            String wshysjzsh = "";
            try {
                /*sysp2 = new SysParamParam();
                sysp2.setParamCode("bgdyxtcs");
                sysp2.setField("wshysjzsh");
                sysp2.setClassifyCode(mainInfo.getRptGroup());
                kcflrdstndtmLst = sysParamValueService.findSysParamFieldAndValueListByCode(sysp2);
                wshysjzsh = kcflrdstndtmLst.get(0).getValue();*/
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "wshysjzsh", mainInfo.getRptGroup(), null);
                wshysjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                //TODO
            }
            /*检验、审核医生相同禁止审核 jyysshysxtjzsh*/
            String jyysshysxtjzsh = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "jyysshysxtjzsh", mainInfo.getRptGroup(), null);
                jyysshysxtjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                //TODO
            }
            /*检验结果包含以下值时禁止审核(,分隔) jyjgbhyxzsjzsh*/
            String jyjgbhyxzsjzsh = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "jyjgbhyxzsjzsh", mainInfo.getRptGroup(), null);
                jyjgbhyxzsjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                //TODO
            }
            /*无病人姓名禁止审核 wbrxmjzsh*/
            String wbrxmjzsh = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(mainInfo.getOrgId(), "wbrxmjzsh", mainInfo.getRptGroup(), null);
                wbrxmjzsh = paramResult.getValueStr();
            } catch (Exception e) {
                //TODO
            }
            LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();
            _labrptresultmapper.eq(LabRptresult::getMaininfoId, mainInfo.getId());
            _labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
            List<LabRptresult> rptresultlist = labRptresultMapper.selectList(_labrptresultmapper);
            /*检验结果小于0,禁止审核*/
            if (!BeanUtil.isEmpty(p2Str) && p2Str.equals("1")) {
                boolean islezero = false;
                for (LabRptresult m : rptresultlist) {
                    try {
                        BigDecimal res = new BigDecimal(m.getTestResult());
                        if (BeanUtil.isEmpty(res) && res.compareTo(new BigDecimal(0)) < 0) {
                            islezero = true;
                            break;
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
                if (islezero) {
                    throw new RuntimeException("检验结果小于0,禁止审核");
                }
            }
            /*检验结果为空时,禁止审核*/
            if (!BeanUtil.isEmpty(jyjgwksjzsh) && jyjgwksjzsh.equals("1")) {
                if (rptresultlist.isEmpty()) {
                    throw new RuntimeException("检验结果为空时,禁止审核");
                }
                boolean isempty = false;
                for (LabRptresult m : rptresultlist) {
                    try {
                        if (StrUtil.isEmpty(m.getTestResult())) {
                            isempty = true;
                            break;
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
                if (isempty) {
                    throw new RuntimeException("检验结果为空时,禁止审核");
                }
            }
            /*无检验医生,禁止审核*/
            if (!BeanUtil.isEmpty(wjyysjzsh) && wjyysjzsh.equals("1")) {
                if (BeanUtil.isEmpty(mainInfo.getTestDoctor())) {
                    throw new RuntimeException("无检验医生,禁止审核");
                }
            }
            /*无审核医生禁止审核*/
            if (!BeanUtil.isEmpty(wshysjzsh) && wshysjzsh.equals("1")) {
                if (BeanUtil.isEmpty(mainInfo.getChkDoctor())) {
                    throw new RuntimeException("无审核医生,禁止审核");
                }
            }
            /*检验、审核医生相同禁止审核*/
            if (!BeanUtil.isEmpty(jyysshysxtjzsh) && jyysshysxtjzsh.equals("1")) {
                if (!BeanUtil.isEmpty(mainInfo.getChkDoctor()) && !BeanUtil.isEmpty(mainInfo.getTestDoctor()) && mainInfo.getChkDoctor().equals(mainInfo.getTestDoctor())) {
                    throw new RuntimeException("检验、审核医生相同,禁止审核");
                }
            }
            /*检验结果包含以下值时禁止审核(,分隔)*/
            if (!BeanUtil.isEmpty(jyjgbhyxzsjzsh) && !jyjgbhyxzsjzsh.equals("")) {
                boolean iscontains = false;
                String[] cns = jyjgbhyxzsjzsh.contains(",") ? jyjgbhyxzsjzsh.split(",") : new String[]{jyjgbhyxzsjzsh};
                for (LabRptresult m : rptresultlist) {
                    try {
                        for (String mm : cns) {
                            if (!BeanUtil.isEmpty(m.getTestResult()) && m.getTestResult().contains(mm)) {
                                iscontains = true;
                                break;
                            }
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
                if (iscontains) {
                    throw new RuntimeException("检验结果包含以下值时禁止审核,禁止审核," + jyjgbhyxzsjzsh);
                }
            }
            /*无病人姓名禁止审核*/
            if (!BeanUtil.isEmpty(wbrxmjzsh) && wbrxmjzsh.equals("1")) {
                if (BeanUtil.isEmpty(mainInfo.getPatNa())) {
                    throw new RuntimeException("无病人姓名,禁止审核");
                }
            }

            /*重新计算检验结果*/
            labRptresultService.reCalcRptRssults(mainInfo);

            mainInfo.setIsChk(chkState);

            //判断进行数据加密
            if (chkState.equals(new BigDecimal(2)) && StringUtils.isNotBlank(caType)) {
                StringBuffer dataStr = new StringBuffer();
                dataStr.append(mainInfo.getPatNo());
                dataStr.append("|");
                dataStr.append(mainInfo.getPatNa());
                dataStr.append("|");
                dataStr.append(mainInfo.getSex());
                dataStr.append("|");
                dataStr.append(mainInfo.getAge());
                dataStr.append("|");
                dataStr.append(mainInfo.getPatType());
                dataStr.append("|");
                dataStr.append(mainInfo.getReqPurpose());
                dataStr.append("|");
                dataStr.append(mainInfo.getReqNo());
                dataStr.append("|");
                dataStr.append(DateUtil.format(mainInfo.getSampleda(), "yyyyMMdd"));
                dataStr.append("|");
                dataStr.append(mainInfo.getSampleNo());
                dataStr.append("结果：");

                MPJLambdaWrapper<LabRptresult> rptresul = new MPJLambdaWrapper<>();
                rptresul.selectAll(LabRptresult.class);
                rptresul.selectAs("itmdict", LabItemDict::getUnit, LabRptresult::getItemUnit);
                rptresul.eq(LabRptresult::getSampleNo, mainInfo.getSampleNo());
                rptresul.eq(LabRptresult::getRptGroup, mainInfo.getRptGroup());
                Timestamp startTime1 = Timestamp.valueOf(mainInfo.getSampleda().toString().substring(0, 10) + " 00:00:00");
                Timestamp endTime1 = Timestamp.valueOf(mainInfo.getSampleda().toString().substring(0, 10) + " 23:59:59");
                rptresul.ge(LabRptresult::getSampleda, startTime1);
                rptresul.le(LabRptresult::getSampleda, endTime1);
                rptresul.leftJoin(LabItemDict.class, "itmdict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
                rptresul.eq(LabRptresult::getDelFlag, 0);
                rptresul.orderByAsc(LabItemDict::getSeq);
                List<LabRptresult> labRptresultList = labRptresultMapper.selectList(rptresul);
                for (LabRptresult item11 : labRptresultList) {
                    dataStr.append(item11.getItemNo() + item11.getTestResult());
                }
                SysUser user = RedisUserManager.getUser();
                //优抚ca原始数据签名
                if (StringUtils.isNotBlank(caType) && caType.equals("1") && StringUtils.isNotBlank(user.getInitializer())) {
                    try {
                        AdvanceSignClient client = new AdvanceSignClient("E:\\Limp\\lis_server\\conf\\cssconfig.properties");
                        NewConfig config = client.getConfig();
                        SymmKeyParams symmParams = new SymmKeyNo(config.getTenantId());
                        // 对称加密
                        byte[] endata = client.symmEncrypt(symmParams, dataStr.toString().getBytes());
                        String signResult = new String(Base64.encode(endata));
                        log.error("base64的对称加密结果为：" + signResult);
                        if (StrUtil.isNotEmpty(signResult)) {
                            mainInfo.setCaSignOri(dataStr.toString());
                            mainInfo.setCaSignSec(signResult);
                        }

                    } catch (NewCSSException e) {
                        log.error("Ca加密失败错误号为：" + e.getCode());
                        log.error("错误描述为: " + e.getDescription());
                        log.error("日志标识码: " + e.getSerialNumber());
                    }
                }

            }

            int i = labMaininfoMapper.updateById(mainInfo);
            if (i <= 0) {
                return null;
            }
            /*标本流程状态记录*/
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                /*审核后生成状态记录*/
                LabMainState reqState1 = new LabMainState();
                reqState1.setMaininfoId(mainInfo.getId());
                reqState1.setStateCode("100");
                String txt = "";
                if (mainInfo.getIsChk().equals(new BigDecimal(1))) {
                    reqState1.setStateCode("99");
                    txt = "初审";
                }
                if (mainInfo.getIsChk().equals(new BigDecimal(2))) {
                    txt = "审核";
                }
                reqState1.setStateValue(txt + "状态");
                reqState1.setCreator(mainInfo.getChkDoctor());
                reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + txt);
                labMainStateService.save(reqState1);

                if (StringUtils.isNotBlank(mainInfo.getReqNo())) {
                    /*标本状态记录*/
                    LabReqMain rmEntry = StringUtils.isNotBlank(mainInfo.getReqNo()) ? labMainInfoServiceBak.getLabReqMainEntity(mainInfo.getReqNo()) : null;
                    LabReqState reqState = new LabReqState();
                    reqState.setReqMainId(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getId() : "");
                    reqState.setSampleda(mainInfo.getSampleda());
                    reqState.setSampleNo(mainInfo.getSampleNo());
                    reqState.setRptGroup(mainInfo.getRptGroup());
                    reqState.setReqNo(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                    reqState.setStateCode(reqState1.getStateCode());
                    reqState.setStateValue(reqState1.getStateValue());
                    reqState.setOrgId(mainInfo.getOrgId());
                    reqState.setCreator(sysUser.getId());
                    String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + txt + ",标本号:" + (BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                    reqState.setRemark(rmk);
                    reqState.setSeq(labReqStateService.getMaxCount(mainInfo.getReqNo()));
                    labReqStateService.save(reqState);

                    if (BeanUtil.isNotEmpty(rmEntry)) {
                        rmEntry.setState(reqState1.getStateCode());
                        rmEntry.setStateNa(reqState1.getStateValue());
                        labReqMainService.saveOrUpdate(rmEntry);
                    }
                }
            }).start();
            /*审核后,先删除已有报告记录，再生成报告记录*/
            try {
                Result r = previewRpt(mainInfo, 1);
            } catch (Exception exception) {
                //ToDo
            }

            return mainInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 更改完审核人、检验人后更新上机记录数据
     *
     * @param input 入参
     */
    @Override
    public Result updateTestChkDoctorAfterAuth(UptMainInfoTextChkDoctorDto input) throws JsonProcessingException {
        return labMainInfoServiceBak.getInfo(input);
    }

    @Override
    public Result mergeTestList(LabMainInfoMerge input) {
        return labMaininfoServiceExtend.mergeTestListNew(input);
    }

    /**
     * 取消审核
     *
     * @param labMaininfo
     */
    @Override
    public Result unChkMainInfo(LabMaininfo labMaininfo) throws JsonProcessingException {

        LabMaininfo mainInfo = findLastLabMainInfo(labMaininfo);
        if (BeanUtil.isEmpty(mainInfo.getIsChk()) || mainInfo.getIsChk().equals(new BigDecimal(0))) {
            return Result.succ(mainInfo);
        }
        if (!BeanUtil.isEmpty(mainInfo.getIsChk()) && mainInfo.getIsChk().equals(new BigDecimal(1))) {
            //取消初审
            mainInfo.setIsChk(new BigDecimal(0));
            mainInfo.setUnchkTime(new Timestamp(System.currentTimeMillis()));
            labMaininfoMapper.updateById(mainInfo);
            //this.updateMaininfo(mainInfo);/*检验记录同步申请*/
            /*标本流程状态记录*/
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                //添加状态记录
                LabMainState reqState1 = new LabMainState();
                reqState1.setMaininfoId(mainInfo.getId());
                reqState1.setStateCode("140");
                String txt = "取消初审";
                reqState1.setStateValue(txt);
                if (StringUtils.isBlank(labMaininfo.getUnChkDoctor())) {
                    reqState1.setCreator(sysUser.getId());
                    reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + txt);
                } else {
                    reqState1.setCreator(labMaininfo.getUnChkDoctor());
                    reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + labMaininfo.getUnChkDoctorNa() + "," + txt);
                }
                labMainStateService.save(reqState1);

                /*标本状态记录*/
                if (StringUtils.isNotBlank(labMaininfo.getReqNo())) {
                    /*标本状态*/
                    LabReqMain rmEntry = labMainInfoServiceBak.getLabReqMainEntity(labMaininfo.getReqNo());
                    LabReqState reqState = new LabReqState();
                    reqState.setReqMainId(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getId() : "");
                    reqState.setSampleda(labMaininfo.getSampleda());
                    reqState.setSampleNo(labMaininfo.getSampleNo());
                    reqState.setRptGroup(labMaininfo.getRptGroup());
                    reqState.setReqNo(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                    reqState.setStateCode(reqState1.getStateCode());
                    reqState.setStateValue(txt);
                    reqState.setRemark(reqState1.getRemark());
                    reqState.setOrgId(mainInfo.getOrgId());
                    reqState.setCreator(sysUser.getId());
                    reqState.setSeq(labReqStateService.getMaxCount(labMaininfo.getReqNo()));
                    labReqStateService.save(reqState);

                    if (BeanUtil.isNotEmpty(rmEntry)) {
                        rmEntry.setState(reqState1.getStateCode());
                        rmEntry.setStateNa(txt);
                        labReqMainService.saveOrUpdate(rmEntry);
                    }
                }

            }).start();

        }
        if (!BeanUtil.isEmpty(mainInfo.getIsChk()) && (mainInfo.getIsChk().intValue() + "").equals(new BigDecimal(2).toString())) {
            /*标本审核后超过____分钟禁止取消审核 */
            SysParamParam sysp1 = new SysParamParam();
            sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("cgfzsjzsh");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if (StringUtils.isNotBlank(r1.get(0).getValue()) && !BeanUtil.isEmpty(mainInfo.getChkTime())) {
                    try {
                        //Timestamp endTime = Timestamp.valueOf(labMaininfo.getSampleDaStr() + " 23:59:59");
                        int minute = Integer.parseInt(r1.get(0).getValue());
                        DateTime lastAllowDate = DateUtil.offsetMinute(mainInfo.getChkTime(), minute);
                        DateTime currDateTime = DateUtil.offsetMinute(new Timestamp(System.currentTimeMillis()), 0);

                        if (currDateTime.compareTo(lastAllowDate) > 0) {
                            return Result.fail("标本审核后超过" + minute + "分钟禁止取消审核");
                        }
                    } catch (Exception e) {
                        //TODO
                    }
                }
            }

            //取消审核
            mainInfo.setIsChk(new BigDecimal(0));
            try {
                /*取消审核时保留审核时间   qxshsblshsj*/
                SysParamParam qxshsblshsj = new SysParamParam();
                qxshsblshsj.setParamCode("bgdyxtcs");
                qxshsblshsj.setField("qxshsblshsj");
                qxshsblshsj.setClassifyCode(mainInfo.getRptGroup());
                List<SysParamFieldValueDto> qxshsblshsjLst = sysParamValueService.findSysParamFieldAndValueListByCode(qxshsblshsj);
                String qxshsblshsjStr = qxshsblshsjLst.isEmpty() ? "" : qxshsblshsjLst.get(0).getValue();
                if (StringUtils.isEmpty(qxshsblshsjStr) || !qxshsblshsjStr.equals("1")) {
                    mainInfo.setChkTime(null);
                }
            } catch (JsonProcessingException e) {
                mainInfo.setChkTime(null);
            }

            SysUser sysUser = RedisUserManager.getUser();
            try {
                List<LabMaininfoCancleaudit> cancleAuditList = labMaininfo.getCancleAuditList();
                if (CollectionUtils.isNotEmpty(cancleAuditList)) {
                    List<LabMaininfoCancleaudit> dataList = new ArrayList<>();
                    cancleAuditList.forEach(a -> {
                        a.setOperatTime(Timestamp.valueOf(DateUtil.now()));
                        a.setName(a.getReason());
                        a.setRptGroup(labMaininfo.getRptGroup());
                        a.setSampleda(labMaininfo.getSampleda());
                        a.setSampleNo(labMaininfo.getSampleNo());
                        a.setReqNo(labMaininfo.getReqNo());
                        a.setOperator(sysUser.getUsername());
                        dataList.add(a);
                    });
                    labMaininfoCancleauditService.saveBatch(dataList);
                }
            } catch (Exception e) {
                log.error("保存消审原因失败");
            }

            labMaininfoMapper.updateById(mainInfo);

            //假删掉报告单
            LambdaQueryWrapper<LabRptmain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabRptmain::getMainInfoId, mainInfo.getId()).eq(LabRptmain::getDelFlag, 0);
            labRptmainMapper.delete(lambdaQueryWrapper);

            /*标本流程状态记录*/
            new Thread(() -> {
                //添加状态记录
                LabMainState reqState1 = new LabMainState();
                reqState1.setMaininfoId(mainInfo.getId());
                reqState1.setStateCode("140");//mainInfo.getIsChk().toString());
                String txt = "取消审核";
                reqState1.setStateValue(txt);

                if (BeanUtil.isEmpty(labMaininfo.getUnChkDoctor())) {
                    reqState1.setCreator(sysUser.getId());
                    reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + txt);
                } else {
                    reqState1.setCreator(labMaininfo.getUnChkDoctor());
                    reqState1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + labMaininfo.getUnChkDoctorNa() + "," + txt);
                }
                labMainStateService.save(reqState1);

                /*标本状态记录*/
                if (StringUtils.isNotBlank(labMaininfo.getReqNo())) {
                    /*标本状态*/
                    LabReqMain rmEntry = labMainInfoServiceBak.getLabReqMainEntity(labMaininfo.getReqNo());
                    LabReqState reqState = new LabReqState();
                    reqState.setReqMainId(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getId() : "");
                    reqState.setSampleda(labMaininfo.getSampleda());
                    reqState.setSampleNo(labMaininfo.getSampleNo());
                    reqState.setRptGroup(labMaininfo.getRptGroup());
                    reqState.setReqNo(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                    reqState.setStateCode(reqState1.getStateCode());
                    reqState.setStateValue(txt);
                    reqState.setRemark(reqState1.getRemark());
                    reqState.setOrgId(mainInfo.getOrgId());
                    reqState.setCreator(sysUser.getId());
                    reqState.setSeq(labReqStateService.getMaxCount(labMaininfo.getReqNo()));
                    labReqStateService.save(reqState);

                    if (BeanUtil.isNotEmpty(rmEntry)) {
                        rmEntry.setState(reqState1.getStateCode());
                        rmEntry.setStateNa(txt);
                        labReqMainService.saveOrUpdate(rmEntry);
                    }
                }
            }).start();

            LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysInterface::getDelFlag, 0);
            wrapper.eq(SysInterface::getIsEnable, 1);
            wrapper.eq(SysInterface::getOrgId, mainInfo.getOrgId());
            List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
            List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
            //标本消申
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                /*发布报告相关*/
                for (String webUrl : collect) {
                    //消审走报告发布传delete
                    Map releaseReportMap = new HashMap();
                    String releaseReport = webUrl + "/public/releaseReport";
                    releaseReportMap.put("orgId", labMaininfo.getOrgId());
                    releaseReportMap.put("mainInfoId", mainInfo.getId());
                    releaseReportMap.put("username", sysUser.getUsername());
                    releaseReportMap.put("realname", sysUser.getRealname());
                    String publishReport = HttpUtil.createPost(releaseReport).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();

                    JSONObject releaseObject = new JSONObject(publishReport);
                    JSONObject releaseStatus = releaseObject.getJSONObject("status");
                    String releaseCode = releaseStatus.get("code").toString();
                    if (!"400".equals(releaseCode)) {
                        String updateUrl = webUrl + "/public/updateReportStatus";
                        Map<String, Object> updateMap = new HashMap<>();
                        //标本消申
                        updateMap.put("status", "99");
                        updateMap.put("reqNo", labMaininfo.getReqNo());
                        updateMap.put("patType", labMaininfo.getPatType());
                        updateMap.put("chkDoctor", labMaininfo.getChkDoctor());
                        updateMap.put("testDoctor", labMaininfo.getTestDoctor());
                        updateMap.put("patType", labMaininfo.getPatType());
                        updateMap.put("samplingTime", BeanUtil.isEmpty(labMaininfo.getSamplingTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getSamplingTime()));
                        updateMap.put("signTime", BeanUtil.isEmpty(labMaininfo.getSignTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getSignTime()));
                        updateMap.put("operateTime", BeanUtil.isEmpty(labMaininfo.getTestTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getTestTime()));
                        updateMap.put("reportTime", BeanUtil.isEmpty(labMaininfo.getChkTime()) ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getChkTime()));
                        updateMap.put("orgId", labMaininfo.getOrgId());
                        updateMap.put("username", sysUser.getUsername());
                        updateMap.put("realname", sysUser.getRealname());
                        updateMap.put("id", labMaininfo.getId());
                        String changeStatus = HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();

                        //消审走报告发布需要撤销掉报告单(伊通需要)
                        Map releaseReportMap1 = new HashMap();
                        String zfReportUrl = webUrl + "/public/zfReleaseReport";
                        releaseReportMap1.put("orgId", labMaininfo.getOrgId());
                        releaseReportMap1.put("mainInfoId", mainInfo.getId());
                        releaseReportMap1.put("username", sysUser.getUsername());
                        releaseReportMap1.put("realname", sysUser.getRealname());
                        HttpUtil.createPost(zfReportUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap1)).contentType("application/json").execute().body();
                    }

                    String releaseReportHL7 = webUrl + "/cancleReport";
                    HttpUtil.createPost(releaseReportHL7).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();

                }
            }
        }
        //lis调用接口平台取消审核
        return labMainInfoServiceBak.unChkMainInfo(mainInfo);
    }

    /**
     * 批量取消审核
     *
     * @param input
     */
    @Override
    public Result unChkMainInfoMany(LabMainInfoBatchUnChk input) throws JsonProcessingException {
        for (LabMaininfo item : input.getLabMaininfoList()) {
            if (BeanUtil.isEmpty(item)) {
                continue;
            }
            if (!BeanUtil.isEmpty(input.getUnchkState()) && input.getUnchkState().equals(1) && !BeanUtil.isEmpty(item.getIsChk()) && !item.getIsChk().equals(new BigDecimal(1))) {
                continue;
            }
            if (!BeanUtil.isEmpty(input.getUnchkState()) && input.getUnchkState().equals(2) && !BeanUtil.isEmpty(item.getIsChk()) && !item.getIsChk().equals(new BigDecimal(2))) {
                continue;
            }
            unChkMainInfo(item);
        }
        return Result.succ(1, "操作完成", null);
    }

    public Integer replaceLetter(String keyValue) {
        Integer k = -1;
        try {
            for (Map.Entry<String, Integer> m : SortMappers.SORT_CONSTANT_MAP.entrySet()) {
                if (keyValue.contains(m.getKey())) {
                    keyValue = keyValue.replace(m.getKey(), m.getValue().toString());
                }
            }
            k = Integer.parseInt(keyValue);
        } catch (Exception exception) {
            k = 999999999;
        }
        return k;
    }

    /**
     * LabMainInfo排序处理
     *
     * @param maininfos 待排序检验记录
     */
    public void sortLabMainInfo(List<LabMaininfo> maininfos) {
        for (LabMaininfo item : maininfos) {
            try {
                if (!BeanUtil.isEmpty(item.getSampleNo())) {
                    String a = item.getSampleNo();
                    for (Map.Entry<String, Integer> m : SortMappers.SORT_CONSTANT_MAP.entrySet()) {
                        if (item.getSampleNo().contains(m.getKey())) {
                            a = a.replace(m.getKey(), m.getValue().toString());
                        }
                    }
                    item.setSeqNo(StringUtils.isEmpty(a) ? 999999999 : Integer.parseInt(a));
                }
            } catch (NumberFormatException e) {
                item.setSeqNo(999999999);
            }
        }
    }

    /**
     * 批量删除检验记录
     *
     * @param input
     */
    @Override
    public Result LabMainInfoBatchDelete(LabMainInfoBatchDelete input) {
        if (BeanUtil.isEmpty(input.getSampleda())) {
            return Result.fail("检验日期为空");
        }
        if (BeanUtil.isEmpty(input.getRptGroup())) {
            return Result.fail("报告单元为空");
        }
        if (input.getRange().isEmpty()) {
            return Result.fail("标本号范围为空");
        }
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getRptGroup, input.getRptGroup());

        Timestamp startTime = Timestamp.valueOf(input.getSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(input.getSampleda().substring(0, 10) + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);

        Integer i = 0;
        for (SampleNoRange itm : input.getRange()) {
            if (BeanUtil.isEmpty(itm.getS()) || BeanUtil.isEmpty(itm.getE())) {
                return Result.fail((i + 1) + "行,开始号段或结束号段不允许为空");
            }
            i++;
        }

        List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);

        sortLabMainInfo(list);

        List<Predicate<LabMaininfo>> dynamicPredicates = new ArrayList<>();

        for (SampleNoRange itm : input.getRange()) {
            dynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm.getS()) && p.getSeqNo() <= replaceLetter(itm.getE()));
        }

        List<LabMaininfo> list1 = list.stream().filter(t -> dynamicPredicates.stream().anyMatch(p -> p.test(t))).collect(Collectors.toList());

        if (list1.isEmpty()) {
            return Result.succ(1, "没有要删除的项", null);
        }

        List<LabMaininfo> listChk1 = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk()) && (p.getIsChk().compareTo(new BigDecimal(1)) == 0 || p.getIsChk().compareTo(new BigDecimal(2)) == 0)).collect(Collectors.toList());

        if (!listChk1.isEmpty()) {
            return Result.fail("号段中存在已初审或已审核的数据");
        }

        List<LabMaininfo> listLock = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsLock()) && p.getIsLock().equals(1)).collect(Collectors.toList());

        if (!listLock.isEmpty()) {
            return Result.fail("号段中存在已锁定的数据");
        }

        List<String> mIds = list1.stream().map(LabMaininfo::getId).collect(Collectors.toList());
        int i1 = labMaininfoMapper.deleteBatchIds(mIds);
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("labMaininfoList", list1);
        if (i1 > 0) {
            //批量删除LabRptresult
            List<String> sampleNoList = list1.stream().map(LabMaininfo::getSampleNo).collect(Collectors.toList());
            if (ToolsUtils.isNotEmpty(sampleNoList)) {
                LambdaQueryWrapper<LabRptresult> delLabRptresultWrapper = new LambdaQueryWrapper<>();
                delLabRptresultWrapper.ge(LabRptresult::getSampleda, startTime);
                delLabRptresultWrapper.le(LabRptresult::getSampleda, endTime);
                delLabRptresultWrapper.eq(LabRptresult::getRptGroup, input.getRptGroup());
                delLabRptresultWrapper.eq(LabRptresult::getDelFlag, 0);
                delLabRptresultWrapper.in(LabRptresult::getSampleNo, sampleNoList);
                int delete = labRptresultMapper.delete(delLabRptresultWrapper);

            }

            return Result.succ(1, "批量删除成功", returnMap);

        } else {
            return Result.succ(1, "批量删除失败", returnMap);

        }

    }

    /**
     * 批量审核检验记录
     *
     * @param input
     */
    @Override
    public Result LabMainInfoBatchChk(LabMainInfoBatchChk input) {
        if (BeanUtil.isEmpty(input.getSampleda())) {
            return Result.fail("检验日期为空");
        }
        if (BeanUtil.isEmpty(input.getRptGroup())) {
            return Result.fail("报告单元为空");
        }
        if (input.getRange().isEmpty()) {
            return Result.fail("标本号范围为空");
        }
        if (BeanUtil.isEmpty(input.getChkValue())) {
            return Result.fail("审核值为空");
        }
        if (BeanUtil.isEmpty(input.getChkDoctor())) {
            return Result.fail("审核人为空");
        }
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getRptGroup, input.getRptGroup());

        Timestamp startTime = Timestamp.valueOf(input.getSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(input.getSampleda().substring(0, 10) + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);

        Integer i = 0;
        for (SampleNoRange itm : input.getRange()) {
            if (BeanUtil.isEmpty(itm.getS()) || BeanUtil.isEmpty(itm.getE())) {
                return Result.fail((i + 1) + "行,开始号段或结束号段不允许为空");
            }
            i++;
        }

        List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);

        sortLabMainInfo(list);

        List<Predicate<LabMaininfo>> dynamicPredicates = new ArrayList<>();

        for (SampleNoRange itm : input.getRange()) {
            dynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm.getS()) && p.getSeqNo() <= replaceLetter(itm.getE()));
        }

        List<LabMaininfo> list1 = list.stream().filter(t -> dynamicPredicates.stream().anyMatch(p -> p.test(t))).collect(Collectors.toList());

        if (list1.isEmpty()) {
            return Result.succ(0, "没有要审核的项", null);
        }

        if (input.getChkValue().equals(1)) {
            List<LabMaininfo> listChk1 = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk()) && (p.getIsChk().compareTo(new BigDecimal(1)) > 0)).collect(Collectors.toList());

            if (!listChk1.isEmpty()) {
                return Result.fail("号段中存在已审核的数据");
            }
        }


        List<LabMaininfo> listLock = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsLock()) && p.getIsLock().equals(1)).collect(Collectors.toList());

        if (!listLock.isEmpty()) {
            return Result.fail("号段中存在已锁定的数据");
        }

        /*查询是否有未处理的危急值*/
        List<String> miIds = list1.stream().map(p -> p.getId()).collect(Collectors.toList());

        List<LabRptresult> ntAlarms = labRptresultService.getAlarmResultByMainIds(miIds);
        if (!ntAlarms.isEmpty()) {
            return Result.fail("记录中存在未处理的危急值,请先处理危急值");
        }

        for (LabMaininfo item : list1) {
            //item.setIsChk(new BigDecimal(input.getChkValue()));
            item.setChkDoctor(input.getChkDoctor());
            item.setChkDoctorNa(input.getChkDoctorNa());
            item.setChkTime(new Timestamp(System.currentTimeMillis()));

            try {
                item = chkLabMainInfo(item, new BigDecimal(input.getChkValue()), input.getCaType());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if (input.getChkValue().equals(2)) {
            labMainInfoServiceBak.his(list1);
        }
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("labMaininfoList", list1);
        return Result.succ(1, "批量审核完成", returnMap);
    }


    /**
     * 批量审核检验记录（挨个处理）
     *
     * @param input
     */
    @Override
    public Result batchChkLabMaininfo(BachChkBatchChk input) throws JsonProcessingException {
        List<LabMaininfo> list1 = input.getLabMaininfos();

        if (list1.isEmpty()) {
            return Result.succ(0, "没有要审核的项", null);
        }
        /*list1 = list1.stream().filter(p -> BeanUtil.isEmpty(p.getIsChk()) || (p.getIsChk().compareTo(new BigDecimal(1)) <= 0)).collect(Collectors.toList());

        if (list1.isEmpty()) {
            return Result.fail("号段中存在已审核的数据");
        }*/


        //List<LabMaininfo> listLock = list1.stream().filter(p -> BeanUtil.isEmpty(p.getIsLock()) || p.getIsLock().equals(0)).collect(Collectors.toList());

        /*if (listLock.isEmpty()) {
            return Result.fail("号段中存在已锁定的数据");
        }*/

        /*查询是否有未处理的危急值*/
        List<String> miIds = list1.stream().map(LabMaininfo::getId).collect(Collectors.toList());

        List<LabRptresult> ntAlarms = labRptresultService.getAlarmResultByMainIds(miIds);
        /*if (!ntAlarms.isEmpty()) {
            return Result.fail("记录中存在未处理的危急值,请先处理危急值");
        }*/

        List<LabMaininfo> resList = new ArrayList<>();

        for (LabMaininfo item : list1) {
            //item.setIsChk(new BigDecimal(input.getChkValue()));
            if (BeanUtil.isNotEmpty(item.getIsChk()) && item.getIsChk().intValue() == 2) {
                item.setBatchActState(false);
                item.setBatchActMsg("数据已审核");
                resList.add(item);
                continue;
            }

            if (BeanUtil.isNotEmpty(item.getIsLock()) && item.getIsLock().equals(1)) {
                item.setBatchActState(false);
                item.setBatchActMsg("数据已锁定");
                resList.add(item);
                continue;
            }

            LabMaininfo finalItem = item;
            List<LabRptresult> isNoTreatAlarms = ntAlarms.stream().filter(p -> p.getSampleNo().equals(finalItem.getSampleNo()) && p.getRptGroup().equals(finalItem.getRptGroup())).collect(Collectors.toList());

            if (!isNoTreatAlarms.isEmpty()) {
                item.setBatchActState(false);
                item.setBatchActMsg("危急值未处理");
                resList.add(item);
                continue;
            }

            SysUser sysUser = RedisUserManager.getUser();
            if (StringUtils.isNotBlank(input.getChkDoctor())) {
                item.setChkDoctor(input.getChkDoctor());
                item.setChkDoctorNa(input.getChkDoctorNa());
                item.setChkTime(new Timestamp(System.currentTimeMillis()));
            } else if (StringUtils.isBlank(item.getChkDoctor()) && ToolsUtils.isNotEmpty(sysUser)) {
                item.setChkDoctor(sysUser.getUsername());
                item.setChkDoctorNa(sysUser.getRealname());
                item.setChkTime(new Timestamp(System.currentTimeMillis()));
            }

            try {
                item = chkLabMainInfo(item, new BigDecimal(input.getChkValue()), input.getCaType());
                item.setBatchActMsg("操作成功");
                item.setBatchActState(true);
            } catch (Exception e) {
                item.setBatchActState(false);
                item.setBatchActMsg(e.getMessage().replace("java.lang.RuntimeException:", ""));
            }
            resList.add(item);
        }

        if (input.getChkValue().equals(2)) {
            List<LabMaininfo> listLock = resList.stream().filter(p -> p.getBatchActState()).collect(Collectors.toList());
            if (!listLock.isEmpty()) {
                try {
                    labMainInfoServiceBak.his(listLock);
                } catch (Exception e) {
                    for (LabMaininfo m : resList) {
                        if (m.getBatchActState()) {
                            m.setBatchActMsg(e.getMessage().replace("java.lang.RuntimeException:", ""));
                        }
                    }
                }
            }
        }
        return Result.succ(1, "批量审核完成", resList);
    }


    @Override
    public Result bachChkBatchPrint(BachChkBatchChk input) {
        List<LabMaininfo> list = input.getLabMaininfos();
        if (list.isEmpty()) {
            return Result.succ(0, "没有要打印的项", null);
        } else {
            List<String> mIds = list.stream().map(LabMaininfo::getId).collect(Collectors.toList());
            List<LabMaininfo> list1 = labMaininfoMapper.selectBatchIds(mIds);
            List<LabMaininfo> listChk = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk()) && (p.getIsChk().compareTo(new BigDecimal(1)) < 0)).collect(Collectors.toList());
            if (!listChk.isEmpty()) {
                return Result.fail("号段中存在未审核的数据");
            }
            List<LabMaininfo> listLock = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsLock()) && p.getIsLock().equals(1)).collect(Collectors.toList());
            if (!listLock.isEmpty()) {
                return Result.fail("号段中存在已锁定的数据");
            }
            /*打印人*/
            SysUser sysUser = RedisUserManager.getUser();
            for (LabMaininfo item : list1) {
                item.setIsPrint(1);
                item.setPrintDoctor(sysUser.getUsername());
                item.setPrintTime(new Timestamp(System.currentTimeMillis()));
                if (BeanUtil.isEmpty(item.getPrintCount())) {
                    item.setPrintCount(new BigDecimal(0));
                } else {
                    item.setPrintCount(item.getPrintCount().add(BigDecimal.ONE));
                }
            }
            boolean r = this.updateBatchById(list1);
            if (!r) {
                return Result.fail("批量打印失败");
            }
            LambdaQueryWrapper<LabRptmain> queryRptMainWrapper = new LambdaQueryWrapper<>();
            queryRptMainWrapper.eq(LabRptmain::getDelFlag, 0);
            queryRptMainWrapper.in(LabRptmain::getMainInfoId, list1.stream().map(LabMaininfo::getId).collect(Collectors.toList()));

            List<LabRptmain> labRptmainList = labRptmainMapper.selectList(queryRptMainWrapper);
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("labRptmainList", labRptmainList);
            returnMap.put("labMaininfoList", list1);


            return Result.succ(1, "批量打印成功", returnMap);
        }


    }

    /*阳性报表*/
    @Override
    public Result getPositiveReports(GetPositiveReportDto input) {
        return labMaininfoServiceQuery.getPositiveReports(input);
    }

    /*验证标本号是否已经创建*/
    @Override
    public Result validateIsExistMainInfo(LabMaininfo labMaininfo) {
        if (StringUtils.isBlank(labMaininfo.getRptGroup())) {
            return Result.succ(1, "请求完成", null);
        }
        if (StringUtils.isBlank(labMaininfo.getSampleNo())) {
            return Result.succ(1, "请求完成", null);
        }
        if (StringUtils.isBlank(labMaininfo.getSampleDaStr())) {
            return Result.succ(1, "请求完成", null);
        }
        LambdaQueryWrapper<LabMaininfo> q = new LambdaQueryWrapper<>();
        q.eq(LabMaininfo::getDelFlag, 0);
        q.eq(LabMaininfo::getSampleNo, labMaininfo.getSampleNo());
        q.eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup());
        Timestamp startTime = Timestamp.valueOf(labMaininfo.getSampleDaStr() + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(labMaininfo.getSampleDaStr() + " 23:59:59");
        q.ge(LabMaininfo::getSampleda, startTime);
        q.le(LabMaininfo::getSampleda, endTime);
        List<LabMaininfo> list = labMaininfoMapper.selectList(q);
        return Result.succ(1, "请求完成", list);
    }

    /*扫码上机验证*/
    @Override
    public Result validateByScanReqNo(LabMaininfo labMaininfo) {
        return labMaininfoServiceExtend.validateByScanReqNo(labMaininfo);
    }

    @Override
    public void downloadReportExcel(ReportExportExcelParam reportExportExcelParam, HttpServletResponse response) throws IOException {
        labMaininfoExcelService.ExportExcelBac(reportExportExcelParam, response);
    }

    /**
     * 批量打印检验记录
     *
     * @param input
     */
    @Override
    public Result LabMainInfoBatchPrint(LabMainInfoBatchPrint input) {
        if (BeanUtil.isEmpty(input.getSampleda())) {
            return Result.fail("检验日期为空");
        }
        if (BeanUtil.isEmpty(input.getRptGroup())) {
            return Result.fail("报告单元为空");
        }
        if (input.getRange().isEmpty()) {
            return Result.fail("标本号范围为空");
        }

        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getRptGroup, input.getRptGroup());

        Timestamp startTime = Timestamp.valueOf(input.getSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(input.getSampleda().substring(0, 10) + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);

        Integer i = 0;
        for (SampleNoRange itm : input.getRange()) {
            if (BeanUtil.isEmpty(itm.getS()) || BeanUtil.isEmpty(itm.getE())) {
                return Result.fail((i + 1) + "行,开始号段或结束号段不允许为空");
            }
            i++;
        }

        List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);

        sortLabMainInfo(list);

        List<Predicate<LabMaininfo>> dynamicPredicates = new ArrayList<>();

        for (SampleNoRange itm : input.getRange()) {
            dynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm.getS()) && p.getSeqNo() <= replaceLetter(itm.getE()));
        }

        List<LabMaininfo> list1 = list.stream().filter(t -> dynamicPredicates.stream().anyMatch(p -> p.test(t))).collect(Collectors.toList());

        if (list1.isEmpty()) {
            return Result.succ(0, "没有要打印的项", null);
        }

        List<LabMaininfo> listChk = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk()) && (p.getIsChk().compareTo(new BigDecimal(1)) < 0)).collect(Collectors.toList());

        if (!listChk.isEmpty()) {
            return Result.fail("号段中存在未审核的数据");
        }

        List<LabMaininfo> listLock = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsLock()) && p.getIsLock().equals(1)).collect(Collectors.toList());

        if (!listLock.isEmpty()) {
            return Result.fail("号段中存在已锁定的数据");
        }

        /*打印人*/
        SysUser sysUser = RedisUserManager.getUser();

        for (LabMaininfo item : list1) {
            item.setIsPrint(1);
            item.setPrintDoctor(sysUser.getUsername());
            item.setPrintTime(new Timestamp(System.currentTimeMillis()));
            if (BeanUtil.isEmpty(item.getPrintCount())) {
                item.setPrintCount(new BigDecimal(0));
            } else {
                item.setPrintCount(item.getPrintCount().add(BigDecimal.ONE));
            }
        }

        boolean r = this.updateBatchById(list1);

        if (!r) {
            return Result.fail("批量打印失败");
        }

        LambdaQueryWrapper<LabRptmain> queryRptMainWrapper = new LambdaQueryWrapper<>();
        queryRptMainWrapper.eq(LabRptmain::getDelFlag, 0);
        queryRptMainWrapper.in(LabRptmain::getMainInfoId, list1.stream().map(LabMaininfo::getId).collect(Collectors.toList()));

        List<LabRptmain> labRptmainList = labRptmainMapper.selectList(queryRptMainWrapper);
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("labRptmainList", labRptmainList);
        returnMap.put("labMaininfoList", list1);


        return Result.succ(1, "批量打印成功", returnMap);
    }

    /*合并打印报告*/
    @Override
    public Result labMainInfoMergePrint(BatchPrintDto batchPrintDto) throws JsonProcessingException {
        return labMainInfoServiceBak.labMainInfoMergePrint(batchPrintDto);
    }

    /*批量打印报告*/
    @Override
    public Result PrintRptBatch(List<LabMaininfo> labMaininfos) {
        return labMainInfoServiceBak.PrintRptBatch(labMaininfos);
    }

    /**
     * 打印检验记录
     *
     * @param labMaininfo
     */
    @Override
    public Result LabMainInfoPrint(LabMaininfo labMaininfo) {
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getId, labMaininfo.getId());
        LabMaininfo entry = labMaininfoMapper.selectOne(queryWrapper);


        Result r = previewRpt(entry, 2);

        SysUser sysUser = RedisUserManager.getUser();
        entry.setIsPrint(1);
        entry.setPrintDoctor(sysUser.getId());
        entry.setPrintTime(new Timestamp(System.currentTimeMillis()));
        if (BeanUtil.isEmpty(entry.getPrintCount())) {
            entry.setPrintCount(new BigDecimal(0));
        } else {
            entry.setPrintCount(entry.getPrintCount().add(BigDecimal.ONE));
        }

        //上机之后插入状态信息

        /*标本流程状态记录*/
        new Thread(() -> {
            LabMainState reqState1 = new LabMainState();
            reqState1.setMaininfoId(entry.getId());
            reqState1.setStateCode("130");
            reqState1.setStateValue("打印报告");
            reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "打印报告单");
            labMainStateService.save(reqState1);

            /*标本状态记录*/
            if (StringUtils.isNotBlank(entry.getReqNo())) {
                /*标本状态*/
                LabReqMain rmEntry = labMainInfoServiceBak.getLabReqMainEntity(entry.getReqNo());
                LabReqState reqState = new LabReqState();
                reqState.setReqMainId(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getId() : "");
                reqState.setSampleda(entry.getSampleda());
                reqState.setSampleNo(entry.getSampleNo());
                reqState.setRptGroup(entry.getRptGroup());
                reqState.setReqNo(BeanUtil.isNotEmpty(rmEntry) ? rmEntry.getReqNo() : "");
                reqState.setStateCode(reqState1.getStateCode());
                reqState.setOrgId(entry.getOrgId());
                reqState.setCreator(sysUser.getId());
                reqState.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "打印报告单");
                reqState.setStateValue("打印报告");
                reqState.setRemark(reqState1.getRemark());
                reqState.setSeq(labReqStateService.getMaxCount(entry.getReqNo()));
                labReqStateService.save(reqState);

                if (BeanUtil.isNotEmpty(rmEntry)) {
                    rmEntry.setIsPrint(1);
                    rmEntry.setState(reqState1.getStateCode());
                    rmEntry.setStateNa(reqState1.getStateValue());
                    labReqMainService.saveOrUpdate(rmEntry);
                }
            }
        }).start();

        Integer i = labMaininfoMapper.updateById(entry);
        if (i > 0) {
            try {
                List<ReportPreviewDto> lst = (List<ReportPreviewDto>) r.getData();
                return Result.succ(1, "打印成功", lst);
            } catch (Exception exception) {
                return Result.fail("打印失败");
            }
        } else {
            return Result.fail("打印失败");
        }
    }

    //自助机
    @Override
    public Result findLabMainInfos(LabMainInfoDtos mainInfoDto) {
        //可能取出多条数据,循环处理每一条
        SSReportDto reportDto = new SSReportDto();
        try {
            if (StringUtils.isBlank(mainInfoDto.getIdNo()) && (BeanUtil.isEmpty(mainInfoDto.getPatNos()) || mainInfoDto.getPatNos().isEmpty())) {
                return Result.fail("请使用身份证号或者病历号查询");
            }
            //todo 自助机需要修改，orgId为自助机传过来的
            if (StrUtil.isNotEmpty(mainInfoDto.getOrgId())) {
                RedisUserManager.storeKeyValue("skip_filter_orgid", mainInfoDto.getOrgId());
            } else {
                RedisUserManager.storeKeyValue("skip_filter_orgid", "1787488360349155329");
            }
            //根据条件取出标本信息(LAN_MAININFO表数据)
            LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabMaininfo::getDelFlag, 0);

            int days = mainInfoDto.getDays();
            if (days > 0) {
                int abs = -days;
                DateTime dateTime = DateUtil.offsetDay(new Date(), abs);
                Date date = new Date();
                queryWrapper.ge(LabMaininfo::getSampleda, dateTime).le(LabMaininfo::getSampleda, date);
            }

            if (StringUtils.isNotBlank(mainInfoDto.getPattype())) {
                if (!Objects.equals(mainInfoDto.getPattype(), "0")) {
                    List<String> patTypeArr = new ArrayList<>();
                    if (mainInfoDto.getPattype().replace("，", ",").contains(",")) {
                        String[] arr = mainInfoDto.getPattype().split(",");
                        for (String m : arr) {
                            patTypeArr.add(m);
                        }
                    } else {
                        patTypeArr.add(mainInfoDto.getPattype());
                    }
                    queryWrapper.in(LabMaininfo::getPatType, patTypeArr);
                }
            }
            if (!BeanUtil.isEmpty(mainInfoDto) && !BeanUtil.isEmpty(mainInfoDto.getPatNos()) && !mainInfoDto.getPatNos().isEmpty()) {
                queryWrapper.and(p -> p.in(LabMaininfo::getPatNo, mainInfoDto.getPatNos()).or().in(LabMaininfo::getIdNo, mainInfoDto.getPatNos()));
            }

            /*检验科打印完自助机是否可以打印 */
            if (!BeanUtil.isEmpty(mainInfoDto.getReprint()) && !mainInfoDto.getReprint()) {
                queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
            }

            /*是否开启报告单元过滤条件*/
            if (!BeanUtil.isEmpty(mainInfoDto.getIsenablewtfilter()) && mainInfoDto.getIsenablewtfilter()) {
                if (mainInfoDto.getWts() != null && !mainInfoDto.getWts().isEmpty() && mainInfoDto.getWts().size() > 0) {
                    queryWrapper.notIn(LabMaininfo::getRptGroup, mainInfoDto.getWts());
                }
            }

            /*自助机未打印*/
            queryWrapper.and(p -> p.eq(LabMaininfo::getIsAutoPrint, 0).or().isNull(LabMaininfo::getIsAutoPrint));

            List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);

            List<SSReportListDto> list = new ArrayList<>();

            int i = 0;
            for (LabMaininfo mainInfo : labMaininfos) {
                SSReportListDto reportListDto = new SSReportListDto();
                String id = mainInfo.getId();
                LambdaQueryWrapper<LabRptmain> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(LabRptmain::getDelFlag, 0).eq(LabRptmain::getIsFinalReport, 1).eq(LabRptmain::getMainInfoId, id);

                //取出最终报告
                List<LabRptmain> labRptmains = labRptmainMapper.selectList(wrapper);
                if (labRptmains.size() > 0) {
                    if (i == 0) {
                        reportDto.setAge(mainInfo.getAge().toString());
                        reportDto.setPatNa(mainInfo.getPatNa());
                        reportDto.setSex(mainInfo.getSex());
                        reportDto.setPatNo(mainInfo.getPatNo());
                    }
                    reportListDto.setReportId(labRptmains.get(0).getId());
                    reportListDto.setApplicationItems(mainInfo.getTestPurpose());
                    reportListDto.setPrintStatus(mainInfo.getIsAutoPrint() == null || mainInfo.getIsAutoPrint() == 1 ? "0" : mainInfo.getIsAutoPrint().toString());
                    reportListDto.setReportObjectCode(labRptmains.get(0).getRptTemplateCode());
                    reportListDto.setScheduleDate(mainInfo.getTestTime());
                    reportListDto.setStatusText(mainInfo.getIsChk().compareTo(BigDecimal.valueOf(2)) == 0 ? "已检验" : "检验中");
                    reportListDto.setStatusValue(mainInfo.getIsChk().compareTo(BigDecimal.valueOf(2)) == 0 ? true : false);
                    reportListDto.setWlId(mainInfo.getId());
                    reportListDto.setAge(mainInfo.getAge().toString());
                    reportListDto.setPatNa(mainInfo.getPatNa());
                    reportListDto.setPatNo(mainInfo.getPatNo());
                    reportListDto.setSex(mainInfo.getSex());
                    list.add(reportListDto);
                    i++;
                }
            }
            reportDto.setReports(list);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            RedisUserManager.deleteValueByKey("skip_filter_orgid");
        }
        return Result.succ(1, "查询成功", reportDto);
    }

    @Override
    public Result updateMainInfoPrintStatus(UpdateMaininfoAfterAutoPrinted input) {
        try {
            if (input.getPrintStatus() != null && !input.getPrintStatus()) {
                return Result.fail(input.getId() + "," + input.getCarMachineId() + "," + "未执行更新，状态非1");
            }
            //todo 自助机需要修改，orgId为自助机传过来的
            if (StrUtil.isNotEmpty(input.getOrgId())) {
                RedisUserManager.storeKeyValue("skip_filter_orgid", input.getOrgId());
            } else {
                RedisUserManager.storeKeyValue("skip_filter_orgid", "1787488360349155329");
            }
            LambdaUpdateWrapper<LabMaininfo> queryWrapper = new LambdaUpdateWrapper<>();
            queryWrapper.eq(LabMaininfo::getDelFlag, 0);
            queryWrapper.eq(LabMaininfo::getId, input.getId());
            queryWrapper.set(LabMaininfo::getAutoPrintTime, Timestamp.valueOf(DateUtil.now()));
            queryWrapper.set(LabMaininfo::getIsAutoPrint, 1);
            boolean update = this.update(queryWrapper);
            if (!update) {
                return Result.fail(input.getId() + "," + input.getCarMachineId() + "," + "执行更新失败");
            }
            /*标本流程状态记录*/
            new Thread(() -> {
                LabMainState reqState1 = new LabMainState();
                reqState1.setMaininfoId(input.getId());
                reqState1.setStateCode("9100");
                String txt = input.getCarMachineId() + "自助机打印成功," + DateUtil.now();
                reqState1.setStateValue(txt);
                labMainStateService.save(reqState1);
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            RedisUserManager.deleteValueByKey("skip_filter_orgid");
        }
        return Result.succ(1, "更新成功", null);
    }

    @Autowired
    LabRptCampusAreaMapper labRptCampusAreaMapper;

    @Override
    public Result testQueryInfo(TestQueryDto testQueryDto) {

        List<String> campusAreas = testQueryDto.getCampusAreas();
        List<String> rptGroups = testQueryDto.getRptGroups();
        //如何有报告单元，按报告单元查，如果无，则按院区
        if (ToolsUtils.isEmpty(rptGroups)) {
            //如果有院区，则查院区下的报告单元，如果无院区，则查所有
            if (ToolsUtils.isNotEmpty(campusAreas)) {
                MPJLambdaWrapper<LabRptCampusArea> queryWrapper = new MPJLambdaWrapper<>();
                queryWrapper.selectAll(LabRptCampusArea.class);
                queryWrapper.selectAs("rpt", LabRptGroup::getRptGroupName, LabRptCampusArea::getRptGroupName);
                queryWrapper.leftJoin(LabRptGroup.class, "rpt", p -> p.eq(LabRptGroup::getRptGroup, LabRptCampusArea::getRptGroup).eq(LabRptGroup::getDelFlag, 0));
                queryWrapper.in(LabRptCampusArea::getCampusCode, campusAreas)
                        .eq(LabRptCampusArea::getDelFlag, 0);

                List<String> rptGroupList = new ArrayList<>();
                List<LabRptCampusArea> detailList = labRptCampusAreaMapper.selectList(queryWrapper);
                if (ToolsUtils.isNotEmpty(detailList)) {
                    rptGroupList = detailList.stream().map(LabRptCampusArea::getRptGroup).collect(Collectors.toList());
                } else {
                    rptGroupList.add("!@#$%^");
                }
                testQueryDto.setRptGroups(rptGroupList);
            }

        }

        List<TestQueryField> headers = testQueryDto.getQueryFields().stream().sorted(Comparator.comparing(TestQueryField::getReq)).collect(Collectors.toList());
        List<TestQueryField> fieldList = testQueryDto.getQueryFields().stream().sorted(Comparator.comparing(TestQueryField::getReq)).collect(Collectors.toList());
        Iterator<TestQueryField> iterator = fieldList.iterator();
        List<String> list = new ArrayList<>(Arrays.asList("patCount", "specCount", "wlCount", "count", "amount"));
        while (iterator.hasNext()) {
            if (list.contains(iterator.next().getField())) {
                iterator.remove();
            }
        }
        List<TestQueryVo> testQueryVos = new ArrayList<>();
        testQueryDto.setQueryFields(fieldList);
        if ("oracle".equals(pageType)) {
            testQueryVos = labMaininfoMapper.testQueryInfoByOracle(testQueryDto);
        } else {
            testQueryVos = labMaininfoMapper.testQueryInfoBySqlServer(testQueryDto);
        }
        //获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();

        for (TestQueryVo testQueryVo : testQueryVos) {
            if (Objects.nonNull(testQueryVo) && StringUtils.isNotBlank(testQueryVo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(testQueryVo.getPatType())).findFirst().ifPresent(stringObjectMap -> testQueryVo.setPatType((String) stringObjectMap.get("name")));
            }
            if (Objects.nonNull(testQueryVo) && StringUtils.isNotBlank(testQueryVo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(testQueryVo.getSex())).findFirst().ifPresent(stringObjectMap -> testQueryVo.setSex((String) stringObjectMap.get("name")));
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", testQueryVos);
        map.put("headers", headers);
        return Result.succ(1, "查询成功", map);
    }

    @Override
    public Result reqQueryInfo(TestQueryDto testQueryDto) {

        List<String> campusAreas = testQueryDto.getCampusAreas();
        List<String> rptGroups = testQueryDto.getRptGroups();
        //如何有报告单元，按报告单元查，如果无，则按院区
        if (ToolsUtils.isEmpty(rptGroups)) {
            //如果有院区，则查院区下的报告单元，如果无院区，则查所有
            if (ToolsUtils.isNotEmpty(campusAreas)) {
                MPJLambdaWrapper<LabRptCampusArea> queryWrapper = new MPJLambdaWrapper<>();
                queryWrapper.selectAll(LabRptCampusArea.class);
                queryWrapper.selectAs("rpt", LabRptGroup::getRptGroupName, LabRptCampusArea::getRptGroupName);
                queryWrapper.leftJoin(LabRptGroup.class, "rpt", p -> p.eq(LabRptGroup::getRptGroup, LabRptCampusArea::getRptGroup).eq(LabRptGroup::getDelFlag, 0));
                queryWrapper.in(LabRptCampusArea::getCampusCode, campusAreas)
                        .eq(LabRptCampusArea::getDelFlag, 0);

                List<String> rptGroupList = new ArrayList<>();
                List<LabRptCampusArea> detailList = labRptCampusAreaMapper.selectList(queryWrapper);
                if (ToolsUtils.isNotEmpty(detailList)) {
                    rptGroupList = detailList.stream().map(LabRptCampusArea::getRptGroup).collect(Collectors.toList());
                } else {
                    rptGroupList.add("!@#$%^");
                }
                testQueryDto.setRptGroups(rptGroupList);
            }

        }

        List<TestQueryField> headers = testQueryDto.getQueryFields().stream().sorted(Comparator.comparing(TestQueryField::getReq)).collect(Collectors.toList());
        List<TestQueryField> fieldList = testQueryDto.getQueryFields().stream().sorted(Comparator.comparing(TestQueryField::getReq)).collect(Collectors.toList());
        Iterator<TestQueryField> iterator = fieldList.iterator();
        List<String> list = new ArrayList<>(Arrays.asList("patCount", "specCount", "wlCount", "count", "amount"));
        while (iterator.hasNext()) {
            if (list.contains(iterator.next().getField())) {
                iterator.remove();
            }
        }
        List<TestQueryField> groupList = testQueryDto.getQueryFields().stream().sorted(Comparator.comparing(TestQueryField::getReq)).collect(Collectors.toList());
        Iterator<TestQueryField> groupIterator = groupList.iterator();
        List<String> groups = new ArrayList<>(Arrays.asList("patCount", "specCount", "wlCount", "count", "amount", "itemNa"));
        while (groupIterator.hasNext()) {
            if (groups.contains(groupIterator.next().getField())) {
                groupIterator.remove();
            }
        }
        testQueryDto.setQueryFields(fieldList);
        testQueryDto.setIsItem(0);
        if (CollectionUtils.isNotEmpty(fieldList)) {
            for (TestQueryField testQueryField : fieldList) {
                if ("itemNa".equals(testQueryField.getField())) {
                    testQueryDto.setIsItem(1);
                }
            }
        }

        testQueryDto.setGroupFields(groupList);
        List<TestQueryVo> testQueryVos = new ArrayList<>();
        if ("oracle".equals(pageType)) {
            testQueryVos = labMaininfoMapper.reqQueryInfoByOracle(testQueryDto);
        } else {
            testQueryVos = labMaininfoMapper.reqQueryInfoBySqlServer(testQueryDto);
        }
        //获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();

        for (TestQueryVo testQueryVo : testQueryVos) {
            if (Objects.nonNull(testQueryVo) && StringUtils.isNotBlank(testQueryVo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(testQueryVo.getPatType())).findFirst().ifPresent(stringObjectMap -> testQueryVo.setPatType((String) stringObjectMap.get("name")));
            }
            if (Objects.nonNull(testQueryVo) && StringUtils.isNotBlank(testQueryVo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(testQueryVo.getSex())).findFirst().ifPresent(stringObjectMap -> testQueryVo.setSex((String) stringObjectMap.get("name")));
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", testQueryVos);
        map.put("headers", headers);
        return Result.succ(1, "查询成功", map);
    }


    @Override
    public Result batchUpdateRptResultByTemplate(LabTemResultParam param) {
        //批量添加或更新的集合
        List<LabRptresult> batchUpdateReusltList = new ArrayList<>();

        List<String> idList = param.getIdList();
        List<LabTemplateDetail> detailList = param.getDetailList();
        List<LabMaininfo> maininfoList = this.getBaseMapper().selectBatchIds(idList);
        List<LabMaininfo> updateMainList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(maininfoList)) {
            for (LabMaininfo labMaininfo : maininfoList) {
                BigDecimal isChk = labMaininfo.getIsChk();
                Integer isLock = labMaininfo.getIsLock();
                //只要空或者0的数据
                if (isNullOrZero(isChk) && (isNullOrZero(isLock))) {
                    updateMainList.add(labMaininfo);
                }
            }
            if (ToolsUtils.isNotEmpty(updateMainList)) {
                List<String> updateMainIds = updateMainList.stream().map(LabMaininfo::getId).collect(Collectors.toList());
                //根据ID查出细项
                LambdaQueryWrapper<LabRptresult> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(LabRptresult::getDelFlag, 0).in(LabRptresult::getMaininfoId, updateMainIds);
                List<LabRptresult> rptresultList = labRptresultMapper.selectList(queryWrapper);
                //循环可以修改的主信息
                for (LabMaininfo labMaininfo : updateMainList) {
                    //循环要添加的细项
                    for (LabTemplateDetail templateDetail : detailList) {
                        Optional<LabRptresult> first = rptresultList.stream().filter(rpt -> (rpt.getItemNo().equals(templateDetail.getItemNo())) && rpt.getMaininfoId().equals(labMaininfo.getId())).findFirst();
                        if (first.isPresent()) {
                            LabRptresult labRptresult = first.get();
                            labRptresult.setTestResult(templateDetail.getRptResult());
                            batchUpdateReusltList.add(labRptresult);
                        } else {
                            LabRptresult labRptresult = new LabRptresult();
                            labRptresult.setSampleda(labMaininfo.getSampleda());
                            labRptresult.setRptGroup(labMaininfo.getRptGroup());
                            labRptresult.setSampleNo(labMaininfo.getSampleNo());
                            labRptresult.setMaininfoId(labMaininfo.getId());
                            labRptresult.setItemNo(templateDetail.getItemNo());
                            labRptresult.setItemNa(templateDetail.getItemNa());
                            labRptresult.setTestResult(templateDetail.getRptResult());
                            labRptresult.setDisplayOrder(templateDetail.getSeq());
                            batchUpdateReusltList.add(labRptresult);
                        }
                    }
                }
            }
        }
        if (ToolsUtils.isNotEmpty(batchUpdateReusltList)) {
            boolean b = labRptresultService.saveOrUpdateBatch(batchUpdateReusltList);
            if (b) {
                labRptresultService.reCalcRptRssultsMany(maininfoList);
                return Result.succ(1, "更新成功", null);
            } else {
                return Result.fail("更新失败");
            }
        } else {
            return Result.succ(1, "无更新", null);
        }
    }


    /**
     * 根据REQ_NO获取当前标本的结果信息
     *
     * @param reqNo
     */
    @Override
    public Result findRptResultByLabMainReqNo(String reqNo, String rptGroup) {

        if (StringUtils.isEmpty(reqNo)) {
            return Result.succ(1, "reqNo为空", "");
        }
        LambdaQueryWrapper<LabMaininfo> queryMI = new LambdaQueryWrapper<>();
        queryMI.eq(LabMaininfo::getDelFlag, 0);
        queryMI.eq(LabMaininfo::getReqNo, reqNo);
        queryMI.eq(LabMaininfo::getRptGroup, rptGroup);
        queryMI.orderByDesc(LabMaininfo::getSampleda);
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryMI);
        if (CollectionUtils.isEmpty(labMaininfos)) {
            return Result.succ(1, "查无上机记录", "");
        }
        LabMaininfo miEntry = labMaininfos.get(0);
        MPJLambdaWrapper<LabRptresult> queryWrapper = new MPJLambdaWrapper<>();
        //queryWrapper.eq(LabRptresult::getDelFlag, 0).eq(LabRptresult::getMaininfoId, id);
        //queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.distinct().selectAll(LabRptresult.class);
        queryWrapper.selectAs("instr", LabInstrSetup::getInstrName, LabRptresult::getInstrNa);
        queryWrapper.selectAs("dict", LabItemDict::getUnit, LabRptresult::getItemUnit);
        queryWrapper.selectAs("dict", LabItemDict::getSeq, LabRptresult::getDisplayOrder);
        queryWrapper.selectAs("dict", LabItemDict::getIsCalcItem, LabRptresult::getIsCalcItem);
        queryWrapper.selectAs("dict", LabItemDict::getId, LabRptresult::getItemDictId);
        queryWrapper.leftJoin(LabItemDict.class, "dict", p -> p.eq(LabItemDict::getItemNo, LabRptresult::getItemNo).eq(LabItemDict::getRptGroup, LabRptresult::getRptGroup).eq(LabItemDict::getDelFlag, 0));
        queryWrapper.leftJoin(LabInstrSetup.class, "instr", p -> p.eq(LabInstrSetup::getRptGroup, LabRptresult::getRptGroup).eq(LabInstrSetup::getInstrCode, LabRptresult::getInstrCode).eq(LabInstrSetup::getDelFlag, 0));
        queryWrapper.eq(LabRptresult::getDelFlag, 0);
        Timestamp timestamp = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp timestamp1 = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate1 = sdf1.format(timestamp1);
        Timestamp endTime = Timestamp.valueOf(formattedDate1 + " 23:59:59");
        queryWrapper.ge(LabRptresult::getSampleda, startTime);
        queryWrapper.le(LabRptresult::getSampleda, endTime);
        queryWrapper.eq(LabRptresult::getRptGroup, miEntry.getRptGroup());
        queryWrapper.eq(LabRptresult::getSampleNo, miEntry.getSampleNo());
        queryWrapper.orderByAsc(LabRptresult::getDisplayOrder);
        List<LabRptresult> labRptresults = labRptresultMapper.selectList(queryWrapper);

        return Result.succ(1, "查询结果成功", labRptresults);
    }

    private static boolean isNullOrZero(BigDecimal bd) {
        return (bd == null) || bd.compareTo(BigDecimal.ZERO) == 0;
    }

    private static boolean isNullOrZero(Integer bd) {
        return (bd == null) || bd == 0;
    }

    /*获取单个标本号*/
    private List<String> GetAimCode(String code) {
        List<String> codes = new ArrayList<>();

        code = code.replace("，", ",");
        code = code.replace("—", "-");

        String[] codeArray = code.split(",");

        for (String c : codeArray) {
            if (!c.contains("-")) {
                codes.add(c);
            } else {
                String[] arr = code.split("-");
                for (int i = Integer.parseInt(arr[0]); i <= Integer.parseInt(arr[1]); i++) {
                    codes.add(i + "");
                }
            }
        }
        return codes;
    }

    /*获取范围标本号*/
    private Map<String, String> GetRangeCode(String code) {
        Map<String, String> codes = new HashMap<>();
        code = code.replace("，", ",");
        code = code.replace("—", "-");

        String[] codeArray = code.split(",");

        for (String c : codeArray) {
            if (c.contains("-")) {
                int count = 0;
                int len = 0;
                String[] range = c.split("-");
                //仅开始结束号码长度相同时前面补0
                if (range[0].length() == range[1].length()) {
                    len = range[0].length();
                }
                String codeMin = BeanUtil.isEmpty(range[0]) ? "" : range[0];
                String codeMax = BeanUtil.isEmpty(range[1]) ? "" : range[1];

                codes.put(codeMin, codeMax);
            }
        }
        return codes;
    }

    private static String codeAutoIncrement(String minCode) {
        char[] charArr = minCode.toCharArray();
        String str = "";
        for (int i = charArr.length - 1; i >= 0; i--) {
            if (Character.isDigit(charArr[i])) {
                str = charArr[i] + str;
            } else {
                break;
            }
        }
        int curInt = Integer.parseInt(str);
        String _str = String.valueOf(curInt + 1);
        if (_str.length() < minCode.length()) {
            _str = minCode.substring(0, minCode.length() - str.length()) + _str;
        }
        return _str;
    }

    private static List<String> getCodeRangeList(String code) {
        List<String> codes = new ArrayList<>();
        int sortCodeLen = 20;
        code = code.replace("，", ",");
        code = code.replace("—", "-");
        String[] codeArray = code.split(",");
        for (String c : codeArray) {
            if (c.contains("-")) {
                int count = 0;
                int len = 0;
                String[] range = c.split("-");

                if (range[0].length() == range[1].length()) {
                    len = range[0].length();
                }
                String codeMin = range[0];
                String codeMax = range[1];

                String currentCode = codeMin;

                codes.add(range[0]);
                do {
                    currentCode = codeAutoIncrement(currentCode);//codeAutoIncrement(currentCode).substring(sortCodeLen);
                    codes.add(currentCode);
                    count += 1;

                    if (count > 10000) {
                        break;
                    }

                } while (!currentCode.equalsIgnoreCase(codeMax));

            } else {
                codes.add(c);
            }
        }

        return codes;
    }
}
